]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegts.c
Make avi and asf demuxer export palette in palctrl
[ffmpeg] / libavformat / mpegts.c
1 /*
2  * MPEG2 transport stream (aka DVB) demux
3  * Copyright (c) 2002-2003 Fabrice Bellard.
4  *
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.
9  *
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.
14  *
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
18  */
19 #include "avformat.h"
20
21 #include "mpegts.h"
22
23 //#define DEBUG_SI
24
25 /* 1.0 second at 24Mbit/s */
26 #define MAX_SCAN_PACKETS 32000
27
28 /* maximum size in which we look for synchronisation if
29    synchronisation is lost */
30 #define MAX_RESYNC_SIZE 4096
31
32 static int add_pes_stream(MpegTSContext *ts, int pid);
33
34 enum MpegTSFilterType {
35     MPEGTS_PES,
36     MPEGTS_SECTION,
37 };
38
39 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
40
41 typedef struct MpegTSPESFilter {
42     PESCallback *pes_cb;
43     void *opaque;
44 } MpegTSPESFilter;
45
46 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
47
48 typedef void SetServiceCallback(void *opaque, int ret);
49
50 typedef struct MpegTSSectionFilter {
51     int section_index;
52     int section_h_size;
53     uint8_t *section_buf;
54     int check_crc:1;
55     int end_of_section_reached:1;
56     SectionCallback *section_cb;
57     void *opaque;
58 } MpegTSSectionFilter;
59
60 typedef struct MpegTSFilter {
61     int pid;
62     int last_cc; /* last cc code (-1 if first packet) */
63     enum MpegTSFilterType type;
64     union {
65         MpegTSPESFilter pes_filter;
66         MpegTSSectionFilter section_filter;
67     } u;
68 } MpegTSFilter;
69
70 typedef struct MpegTSService {
71     int running:1;
72     int sid;
73     char *provider_name;
74     char *name;
75 } MpegTSService;
76
77 struct MpegTSContext {
78     /* user data */
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 */
82     int set_service_ret;
83
84     int mpeg2ts_raw;  /* force raw MPEG2 transport stream output, if possible */
85     int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
86
87     /* used to estimate the exact PCR */
88     int64_t cur_pcr;
89     int pcr_incr;
90
91     /* data needed to handle file based ts */
92     int stop_parse; /* stop parsing loop */
93     AVPacket *pkt; /* packet containing av data */
94
95     /******************************************/
96     /* private mpegts data */
97     /* scan context */
98     MpegTSFilter *sdt_filter;
99     int nb_services;
100     MpegTSService **services;
101     
102     /* set service context (XXX: allocated it ?) */
103     SetServiceCallback *set_service_cb;
104     void *set_service_opaque;
105     MpegTSFilter *pat_filter;
106     MpegTSFilter *pmt_filter;
107     int req_sid;
108
109     MpegTSFilter *pids[NB_PID_MAX];
110 };
111
112 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
113                                const uint8_t *buf, int buf_size, int is_start)
114 {
115     MpegTSSectionFilter *tss = &tss1->u.section_filter;
116     int len;
117     unsigned int crc;
118     
119     if (is_start) {
120         memcpy(tss->section_buf, buf, buf_size);
121         tss->section_index = buf_size;
122         tss->section_h_size = -1;
123         tss->end_of_section_reached = 0;
124     } else {
125         if (tss->end_of_section_reached)
126             return;
127         len = 4096 - tss->section_index;
128         if (buf_size < len)
129             len = buf_size;
130         memcpy(tss->section_buf + tss->section_index, buf, len);
131         tss->section_index += len;
132     }
133
134     /* compute section length if possible */
135     if (tss->section_h_size == -1 && tss->section_index >= 3) {
136         len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
137         if (len > 4096)
138             return;
139         tss->section_h_size = len;
140     }
141
142     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
143         if (tss->check_crc) {
144             crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
145             if (crc != 0)
146                 goto invalid_crc;
147         }
148         tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
149     invalid_crc:
150         tss->end_of_section_reached = 1;
151     }
152 }
153
154 MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid, 
155                                          SectionCallback *section_cb, void *opaque,
156                                          int check_crc)
157
158 {
159     MpegTSFilter *filter;
160     MpegTSSectionFilter *sec;
161     
162 #ifdef DEBUG_SI
163     printf("Filter: pid=0x%x\n", pid);
164 #endif
165     if (pid >= NB_PID_MAX || ts->pids[pid])
166         return NULL;
167     filter = av_mallocz(sizeof(MpegTSFilter));
168     if (!filter) 
169         return NULL;
170     ts->pids[pid] = filter;
171     filter->type = MPEGTS_SECTION;
172     filter->pid = pid;
173     filter->last_cc = -1;
174     sec = &filter->u.section_filter;
175     sec->section_cb = section_cb;
176     sec->opaque = opaque;
177     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
178     sec->check_crc = check_crc;
179     if (!sec->section_buf) {
180         av_free(filter);
181         return NULL;
182     }
183     return filter;
184 }
185
186 MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid, 
187                                      PESCallback *pes_cb,
188                                      void *opaque)
189 {
190     MpegTSFilter *filter;
191     MpegTSPESFilter *pes;
192
193     if (pid >= NB_PID_MAX || ts->pids[pid])
194         return NULL;
195     filter = av_mallocz(sizeof(MpegTSFilter));
196     if (!filter) 
197         return NULL;
198     ts->pids[pid] = filter;
199     filter->type = MPEGTS_PES;
200     filter->pid = pid;
201     filter->last_cc = -1;
202     pes = &filter->u.pes_filter;
203     pes->pes_cb = pes_cb;
204     pes->opaque = opaque;
205     return filter;
206 }
207
208 void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
209 {
210     int pid;
211
212     pid = filter->pid;
213     if (filter->type == MPEGTS_SECTION)
214         av_freep(&filter->u.section_filter.section_buf);
215     av_free(filter);
216     ts->pids[pid] = NULL;
217 }
218
219 /* autodetect fec presence. Must have at least 1024 bytes  */
220 static int get_packet_size(const uint8_t *buf, int size)
221 {
222     int i;
223
224     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
225         return -1;
226     for(i=0;i<5;i++) {
227         if (buf[i * TS_PACKET_SIZE] != 0x47)
228             goto try_fec;
229     }
230     return TS_PACKET_SIZE;
231  try_fec:
232     for(i=0;i<5;i++) {
233         if (buf[i * TS_FEC_PACKET_SIZE] != 0x47)
234             return -1;
235     }
236     return TS_FEC_PACKET_SIZE;
237 }
238
239 typedef struct SectionHeader {
240     uint8_t tid;
241     uint16_t id;
242     uint8_t version;
243     uint8_t sec_num;
244     uint8_t last_sec_num;
245 } SectionHeader;
246
247 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
248 {
249     const uint8_t *p;
250     int c;
251
252     p = *pp;
253     if (p >= p_end)
254         return -1;
255     c = *p++;
256     *pp = p;
257     return c;
258 }
259
260 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
261 {
262     const uint8_t *p;
263     int c;
264
265     p = *pp;
266     if ((p + 1) >= p_end)
267         return -1;
268     c = (p[0] << 8) | p[1];
269     p += 2;
270     *pp = p;
271     return c;
272 }
273
274 /* read and allocate a DVB string preceeded by its length */
275 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
276 {
277     int len;
278     const uint8_t *p;
279     char *str;
280
281     p = *pp;
282     len = get8(&p, p_end);
283     if (len < 0)
284         return NULL;
285     if ((p + len) > p_end)
286         return NULL;
287     str = av_malloc(len + 1);
288     if (!str)
289         return NULL;
290     memcpy(str, p, len);
291     str[len] = '\0';
292     p += len;
293     *pp = p;
294     return str;
295 }
296
297 static int parse_section_header(SectionHeader *h, 
298                                 const uint8_t **pp, const uint8_t *p_end)
299 {
300     int val;
301
302     val = get8(pp, p_end);
303     if (val < 0)
304         return -1;
305     h->tid = val;
306     *pp += 2;
307     val = get16(pp, p_end);
308     if (val < 0)
309         return -1;
310     h->id = val;
311     val = get8(pp, p_end);
312     if (val < 0)
313         return -1;
314     h->version = (val >> 1) & 0x1f;
315     val = get8(pp, p_end);
316     if (val < 0)
317         return -1;
318     h->sec_num = val;
319     val = get8(pp, p_end);
320     if (val < 0)
321         return -1;
322     h->last_sec_num = val;
323     return 0;
324 }
325
326 static MpegTSService *new_service(MpegTSContext *ts, int sid, 
327                                   char *provider_name, char *name)
328 {
329     MpegTSService *service;
330
331 #ifdef DEBUG_SI
332     printf("new_service: sid=0x%04x provider='%s' name='%s'\n", 
333            sid, provider_name, name);
334 #endif
335
336     service = av_mallocz(sizeof(MpegTSService));
337     if (!service)
338         return NULL;
339     service->sid = sid;
340     service->provider_name = provider_name;
341     service->name = name;
342     dynarray_add(&ts->services, &ts->nb_services, service);
343     return service;
344 }
345
346 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
347 {
348     MpegTSContext *ts = opaque;
349     SectionHeader h1, *h = &h1;
350     const uint8_t *p, *p_end;
351     int program_info_length, pcr_pid, pid, stream_type, desc_length;
352     
353 #ifdef DEBUG_SI
354     printf("PMT:\n");
355     av_hex_dump((uint8_t *)section, section_len);
356 #endif
357     p_end = section + section_len - 4;
358     p = section;
359     if (parse_section_header(h, &p, p_end) < 0)
360         return;
361 #ifdef DEBUG_SI
362     printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
363 #endif
364     if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
365         return;
366
367     pcr_pid = get16(&p, p_end) & 0x1fff;
368     if (pcr_pid < 0)
369         return;
370 #ifdef DEBUG_SI
371     printf("pcr_pid=0x%x\n", pcr_pid);
372 #endif
373     program_info_length = get16(&p, p_end) & 0xfff;
374     if (program_info_length < 0)
375         return;
376     p += program_info_length;
377     if (p >= p_end)
378         return;
379     for(;;) {
380         stream_type = get8(&p, p_end);
381         if (stream_type < 0)
382             break;
383         pid = get16(&p, p_end) & 0x1fff;
384         if (pid < 0)
385             break;
386         desc_length = get16(&p, p_end) & 0xfff;
387         if (desc_length < 0)
388             break;
389         p += desc_length;
390         if (p > p_end)
391             return;
392
393 #ifdef DEBUG_SI
394         printf("stream_type=%d pid=0x%x\n", stream_type, pid);
395 #endif
396
397         /* now create ffmpeg stream */
398         switch(stream_type) {
399         case STREAM_TYPE_AUDIO_MPEG1:
400         case STREAM_TYPE_AUDIO_MPEG2:
401         case STREAM_TYPE_VIDEO_MPEG1:
402         case STREAM_TYPE_VIDEO_MPEG2:
403         case STREAM_TYPE_AUDIO_AC3:
404             add_pes_stream(ts, pid);
405             break;
406         default:
407             /* we ignore the other streams */
408             break;
409         }
410     }
411     /* all parameters are there */
412     ts->set_service_cb(ts->set_service_opaque, 0);
413     mpegts_close_filter(ts, ts->pmt_filter);
414     ts->pmt_filter = NULL;
415 }
416
417 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
418 {
419     MpegTSContext *ts = opaque;
420     SectionHeader h1, *h = &h1;
421     const uint8_t *p, *p_end;
422     int sid, pmt_pid;
423
424 #ifdef DEBUG_SI
425     printf("PAT:\n");
426     av_hex_dump((uint8_t *)section, section_len);
427 #endif
428     p_end = section + section_len - 4;
429     p = section;
430     if (parse_section_header(h, &p, p_end) < 0)
431         return;
432     if (h->tid != PAT_TID)
433         return;
434
435     for(;;) {
436         sid = get16(&p, p_end);
437         if (sid < 0)
438             break;
439         pmt_pid = get16(&p, p_end) & 0x1fff;
440         if (pmt_pid < 0)
441             break;
442 #ifdef DEBUG_SI
443         printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
444 #endif
445         if (sid == 0x0000) {
446             /* NIT info */
447         } else {
448             if (ts->req_sid == sid) {
449                 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid, 
450                                                             pmt_cb, ts, 1);
451                 goto found;
452             }
453         }
454     }
455     /* not found */
456     ts->set_service_cb(ts->set_service_opaque, -1);
457
458  found:
459     mpegts_close_filter(ts, ts->pat_filter);
460     ts->pat_filter = NULL;
461 }
462
463 /* add all services found in the PAT */
464 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
465 {
466     MpegTSContext *ts = opaque;
467     SectionHeader h1, *h = &h1;
468     const uint8_t *p, *p_end;
469     int sid, pmt_pid;
470     char *provider_name, *name;
471     char buf[256];
472
473 #ifdef DEBUG_SI
474     printf("PAT:\n");
475     av_hex_dump((uint8_t *)section, section_len);
476 #endif
477     p_end = section + section_len - 4;
478     p = section;
479     if (parse_section_header(h, &p, p_end) < 0)
480         return;
481     if (h->tid != PAT_TID)
482         return;
483
484     for(;;) {
485         sid = get16(&p, p_end);
486         if (sid < 0)
487             break;
488         pmt_pid = get16(&p, p_end) & 0x1fff;
489         if (pmt_pid < 0)
490             break;
491 #ifdef DEBUG_SI
492         printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
493 #endif
494         if (sid == 0x0000) {
495             /* NIT info */
496         } else {
497             /* add the service with a dummy name */
498             snprintf(buf, sizeof(buf), "Service %x\n", sid);
499             name = av_strdup(buf);
500             provider_name = av_strdup("");
501             if (name && provider_name) {
502                 new_service(ts, sid, provider_name, name);
503             } else {
504                 av_freep(&name);
505                 av_freep(&provider_name);
506             }
507         }
508     }
509     ts->stop_parse = 1;
510
511     /* remove filter */
512     mpegts_close_filter(ts, ts->pat_filter);
513     ts->pat_filter = NULL;
514 }
515
516 void mpegts_set_service(MpegTSContext *ts, int sid,
517                         SetServiceCallback *set_service_cb, void *opaque)
518 {
519     ts->set_service_cb = set_service_cb;
520     ts->set_service_opaque = opaque;
521     ts->req_sid = sid;
522     ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID, 
523                                                 pat_cb, ts, 1);
524 }
525
526 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
527 {
528     MpegTSContext *ts = opaque;
529     SectionHeader h1, *h = &h1;
530     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
531     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
532     char *name, *provider_name;
533
534 #ifdef DEBUG_SI
535     printf("SDT:\n");
536     av_hex_dump((uint8_t *)section, section_len);
537 #endif
538
539     p_end = section + section_len - 4;
540     p = section;
541     if (parse_section_header(h, &p, p_end) < 0)
542         return;
543     if (h->tid != SDT_TID)
544         return;
545     onid = get16(&p, p_end);
546     if (onid < 0)
547         return;
548     val = get8(&p, p_end);
549     if (val < 0)
550         return;
551     for(;;) {
552         sid = get16(&p, p_end);
553         if (sid < 0)
554             break;
555         val = get8(&p, p_end);
556         if (val < 0)
557             break;
558         desc_list_len = get16(&p, p_end) & 0xfff;
559         if (desc_list_len < 0)
560             break;
561         desc_list_end = p + desc_list_len;
562         if (desc_list_end > p_end)
563             break;
564         for(;;) {
565             desc_tag = get8(&p, desc_list_end);
566             if (desc_tag < 0)
567                 break;
568             desc_len = get8(&p, desc_list_end);
569             desc_end = p + desc_len;
570             if (desc_end > desc_list_end)
571                 break;
572 #ifdef DEBUG_SI
573             printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
574 #endif
575             switch(desc_tag) {
576             case 0x48:
577                 service_type = get8(&p, p_end);
578                 if (service_type < 0)
579                     break;
580                 provider_name = getstr8(&p, p_end);
581                 if (!provider_name)
582                     break;
583                 name = getstr8(&p, p_end);
584                 if (!name)
585                     break;
586                 new_service(ts, sid, provider_name, name);
587                 break;
588             default:
589                 break;
590             }
591             p = desc_end;
592         }
593         p = desc_list_end;
594     }
595     ts->stop_parse = 1;
596
597     /* remove filter */
598     mpegts_close_filter(ts, ts->sdt_filter);
599     ts->sdt_filter = NULL;
600 }
601
602 /* scan services in a transport stream by looking at the SDT */
603 void mpegts_scan_sdt(MpegTSContext *ts)
604 {
605     ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID, 
606                                                 sdt_cb, ts, 1);
607 }
608
609 /* scan services in a transport stream by looking at the PAT (better
610    than nothing !) */
611 void mpegts_scan_pat(MpegTSContext *ts)
612 {
613     ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID, 
614                                                 pat_scan_cb, ts, 1);
615 }
616
617 /* TS stream handling */
618
619 enum MpegTSState {
620     MPEGTS_HEADER = 0,
621     MPEGTS_PESHEADER_FILL,
622     MPEGTS_PAYLOAD,
623     MPEGTS_SKIP,
624 };
625
626 /* enough for PES header + length */
627 #define PES_START_SIZE 9
628 #define MAX_PES_HEADER_SIZE (9 + 255)
629
630 typedef struct PESContext {
631     int pid;
632     MpegTSContext *ts;
633     AVFormatContext *stream;
634     AVStream *st;
635     enum MpegTSState state;
636     /* used to get the format */
637     int data_index;
638     int total_size;
639     int pes_header_size;
640     int64_t pts, dts;
641     uint8_t header[MAX_PES_HEADER_SIZE];
642 } PESContext;
643
644 static int64_t get_pts(const uint8_t *p)
645 {
646     int64_t pts;
647     int val;
648
649     pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
650     val = (p[1] << 8) | p[2];
651     pts |= (int64_t)(val >> 1) << 15;
652     val = (p[3] << 8) | p[4];
653     pts |= (int64_t)(val >> 1);
654     return pts;
655 }
656
657 /* return non zero if a packet could be constructed */
658 static void mpegts_push_data(void *opaque,
659                              const uint8_t *buf, int buf_size, int is_start)
660 {
661     PESContext *pes = opaque;
662     MpegTSContext *ts = pes->ts;
663     AVStream *st;
664     const uint8_t *p;
665     int len, code, codec_type, codec_id;
666     
667     if (is_start) {
668         pes->state = MPEGTS_HEADER;
669         pes->data_index = 0;
670     }
671     p = buf;
672     while (buf_size > 0) {
673         switch(pes->state) {
674         case MPEGTS_HEADER:
675             len = PES_START_SIZE - pes->data_index;
676             if (len > buf_size)
677                 len = buf_size;
678             memcpy(pes->header + pes->data_index, p, len);
679             pes->data_index += len;
680             p += len;
681             buf_size -= len;
682             if (pes->data_index == PES_START_SIZE) {
683                 /* we got all the PES or section header. We can now
684                    decide */
685 #if 0
686                 av_hex_dump(pes->header, pes->data_index);
687 #endif
688                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
689                     pes->header[2] == 0x01) {
690                     /* it must be an mpeg2 PES stream */
691                     code = pes->header[3] | 0x100;
692                     if (!((code >= 0x1c0 && code <= 0x1df) ||
693                           (code >= 0x1e0 && code <= 0x1ef) ||
694                           (code == 0x1bd)))
695                         goto skip;
696                     if (!pes->st) {
697                         /* allocate stream */
698                         if (code >= 0x1c0 && code <= 0x1df) {
699                             codec_type = CODEC_TYPE_AUDIO;
700                             codec_id = CODEC_ID_MP2;
701                         } else if (code == 0x1bd) {
702                             codec_type = CODEC_TYPE_AUDIO;
703                             codec_id = CODEC_ID_AC3;
704                         } else {
705                             codec_type = CODEC_TYPE_VIDEO;
706                             codec_id = CODEC_ID_MPEG1VIDEO;
707                         }
708                         st = av_new_stream(pes->stream, pes->pid);
709                         if (st) {
710                             st->priv_data = pes;
711                             st->codec.codec_type = codec_type;
712                             st->codec.codec_id = codec_id;
713                             pes->st = st;
714                         }
715                     }
716                     pes->state = MPEGTS_PESHEADER_FILL;
717                     pes->total_size = (pes->header[4] << 8) | pes->header[5];
718                     /* NOTE: a zero total size means the PES size is
719                        unbounded */
720                     if (pes->total_size)
721                         pes->total_size += 6;
722                     pes->pes_header_size = pes->header[8] + 9;
723                 } else {
724                     /* otherwise, it should be a table */
725                     /* skip packet */
726                 skip:
727                     pes->state = MPEGTS_SKIP;
728                     continue;
729                 }
730             }
731             break;
732             /**********************************************/
733             /* PES packing parsing */
734         case MPEGTS_PESHEADER_FILL:
735             len = pes->pes_header_size - pes->data_index;
736             if (len > buf_size)
737                 len = buf_size;
738             memcpy(pes->header + pes->data_index, p, len);
739             pes->data_index += len;
740             p += len;
741             buf_size -= len;
742             if (pes->data_index == pes->pes_header_size) {
743                 const uint8_t *r;
744                 unsigned int flags;
745
746                 flags = pes->header[7];
747                 r = pes->header + 9;
748                 pes->pts = AV_NOPTS_VALUE;
749                 pes->dts = AV_NOPTS_VALUE;
750                 if ((flags & 0xc0) == 0x80) {
751                     pes->pts = get_pts(r);
752                     r += 5;
753                 } else if ((flags & 0xc0) == 0xc0) {
754                     pes->pts = get_pts(r);
755                     r += 5;
756                     pes->dts = get_pts(r);
757                     r += 5;
758                 }
759                 /* we got the full header. We parse it and get the payload */
760                 pes->state = MPEGTS_PAYLOAD;
761             }
762             break;
763         case MPEGTS_PAYLOAD:
764             if (pes->total_size) {
765                 len = pes->total_size - pes->data_index;
766                 if (len > buf_size)
767                     len = buf_size;
768             } else {
769                 len = buf_size;
770             }
771             if (len > 0) {
772                 AVPacket *pkt = ts->pkt;
773                 if (pes->st && av_new_packet(pkt, len) == 0) {
774                     memcpy(pkt->data, p, len);
775                     pkt->stream_index = pes->st->index;
776                     pkt->pts = pes->pts;
777                     /* reset pts values */
778                     pes->pts = AV_NOPTS_VALUE;
779                     pes->dts = AV_NOPTS_VALUE;
780                     ts->stop_parse = 1;
781                     return;
782                 }
783             }
784             buf_size = 0;
785             break;
786         case MPEGTS_SKIP:
787             buf_size = 0;
788             break;
789         }
790     }
791 }
792
793 static int add_pes_stream(MpegTSContext *ts, int pid)
794 {
795     MpegTSFilter *tss;
796     PESContext *pes;
797
798     /* if no pid found, then add a pid context */
799     pes = av_mallocz(sizeof(PESContext));
800     if (!pes)
801         return -1;
802     pes->ts = ts;
803     pes->stream = ts->stream;
804     pes->pid = pid;
805     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
806     if (!tss) {
807         av_free(pes);
808         return -1;
809     }
810     return 0;
811 }
812
813 /* handle one TS packet */
814 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
815 {
816     AVFormatContext *s = ts->stream;
817     MpegTSFilter *tss;
818     int len, pid, cc, cc_ok, afc, is_start;
819     const uint8_t *p, *p_end;
820
821     pid = ((packet[1] & 0x1f) << 8) | packet[2];
822     is_start = packet[1] & 0x40;
823     tss = ts->pids[pid];
824     if (ts->auto_guess && tss == NULL && is_start) {
825         add_pes_stream(ts, pid);
826         tss = ts->pids[pid];
827     }
828     if (!tss)
829         return;
830
831     /* continuity check (currently not used) */
832     cc = (packet[3] & 0xf);
833     cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
834     tss->last_cc = cc;
835     
836     /* skip adaptation field */
837     afc = (packet[3] >> 4) & 3;
838     p = packet + 4;
839     if (afc == 0) /* reserved value */
840         return;
841     if (afc == 2) /* adaptation field only */
842         return;
843     if (afc == 3) {
844         /* skip adapation field */
845         p += p[0] + 1;
846     }
847     /* if past the end of packet, ignore */
848     p_end = packet + TS_PACKET_SIZE;
849     if (p >= p_end)
850         return;
851     
852     if (tss->type == MPEGTS_SECTION) {
853         if (is_start) {
854             /* pointer field present */
855             len = *p++;
856             if (p + len > p_end)
857                 return;
858             if (len && cc_ok) {
859                 /* write remaning section bytes */
860                 write_section_data(s, tss, 
861                                    p, len, 0);
862             }
863             p += len;
864             if (p < p_end) {
865                 write_section_data(s, tss, 
866                                    p, p_end - p, 1);
867             }
868         } else {
869             if (cc_ok) {
870                 write_section_data(s, tss, 
871                                    p, p_end - p, 0);
872             }
873         }
874     } else {
875         tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque, 
876                                  p, p_end - p, is_start);
877     }
878 }
879
880 /* XXX: try to find a better synchro over several packets (use
881    get_packet_size() ?) */
882 static int mpegts_resync(ByteIOContext *pb)
883 {
884     int c, i;
885
886     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
887         c = url_fgetc(pb);
888         if (c < 0)
889             return -1;
890         if (c == 0x47) {
891             url_fseek(pb, -1, SEEK_CUR);
892             return 0;
893         }
894     }
895     /* no sync found */
896     return -1;
897 }
898
899 /* return -1 if error or EOF. Return 0 if OK. */
900 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
901 {
902     int skip, len;
903
904     for(;;) {
905         len = get_buffer(pb, buf, TS_PACKET_SIZE);
906         if (len != TS_PACKET_SIZE)
907             return AVERROR_IO;
908         /* check paquet sync byte */
909         if (buf[0] != 0x47) {
910             /* find a new packet start */
911             url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
912             if (mpegts_resync(pb) < 0)
913                 return AVERROR_INVALIDDATA;
914             else
915                 continue;
916         } else {
917             skip = raw_packet_size - TS_PACKET_SIZE;
918             if (skip > 0)
919                 url_fskip(pb, skip);
920             break;
921         }
922     }
923     return 0;
924 }
925
926 static int handle_packets(MpegTSContext *ts, int nb_packets)
927 {
928     AVFormatContext *s = ts->stream;
929     ByteIOContext *pb = &s->pb;
930     uint8_t packet[TS_PACKET_SIZE];
931     int packet_num, ret;
932
933     ts->stop_parse = 0;
934     packet_num = 0;
935     for(;;) {
936         if (ts->stop_parse)
937             break;
938         packet_num++;
939         if (nb_packets != 0 && packet_num >= nb_packets)
940             break;
941         ret = read_packet(pb, packet, ts->raw_packet_size);
942         if (ret != 0)
943             return ret;
944         handle_packet(ts, packet);
945     }
946     return 0;
947 }
948
949 static int mpegts_probe(AVProbeData *p)
950 {
951 #if 1
952     int size;
953     size = get_packet_size(p->buf, p->buf_size);
954     if (size < 0)
955         return 0;
956     return AVPROBE_SCORE_MAX - 1;
957 #else
958     /* only use the extension for safer guess */
959     if (match_ext(p->filename, "ts"))
960         return AVPROBE_SCORE_MAX;
961     else
962         return 0;
963 #endif
964 }
965
966 void set_service_cb(void *opaque, int ret)
967 {
968     MpegTSContext *ts = opaque;
969     ts->set_service_ret = ret;
970     ts->stop_parse = 1;
971 }
972
973 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
974    (-1) if not available */
975 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, 
976                      const uint8_t *packet)
977 {
978     int afc, len, flags;
979     const uint8_t *p;
980     unsigned int v;
981
982     afc = (packet[3] >> 4) & 3;
983     if (afc <= 1)
984         return -1;
985     p = packet + 4;
986     len = p[0];
987     p++;
988     if (len == 0)
989         return -1;
990     flags = *p++;
991     len--;
992     if (!(flags & 0x10))
993         return -1;
994     if (len < 6)
995         return -1;
996     v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
997     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
998     *ppcr_low = ((p[4] & 1) << 8) | p[5];
999     return 0;
1000 }
1001
1002 static int mpegts_read_header(AVFormatContext *s,
1003                               AVFormatParameters *ap)
1004 {
1005     MpegTSContext *ts = s->priv_data;
1006     ByteIOContext *pb = &s->pb;
1007     uint8_t buf[1024];
1008     int len, sid;
1009     int64_t pos;
1010     MpegTSService *service;
1011     
1012     if (ap) {
1013         ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1014         ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1015     }
1016
1017     /* read the first 1024 bytes to get packet size */
1018     pos = url_ftell(pb);
1019     len = get_buffer(pb, buf, sizeof(buf));
1020     if (len != sizeof(buf))
1021         goto fail;
1022     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1023     if (ts->raw_packet_size <= 0)
1024         goto fail;
1025     ts->stream = s;
1026     ts->auto_guess = 0;
1027
1028     if (!ts->mpeg2ts_raw) {
1029         /* normal demux */
1030
1031         if (!ts->auto_guess) {
1032             ts->set_service_ret = -1;
1033
1034             /* first do a scaning to get all the services */
1035             url_fseek(pb, pos, SEEK_SET);
1036             mpegts_scan_sdt(ts);
1037             
1038             handle_packets(ts, MAX_SCAN_PACKETS);
1039             
1040             if (ts->nb_services <= 0) {
1041                 /* no SDT found, we try to look at the PAT */
1042                 
1043                 /* First remove the SDT filters from each PID */
1044                 int i;
1045                 for (i=0; i < NB_PID_MAX; i++) {
1046                     if (ts->pids[i])
1047                         mpegts_close_filter(ts, ts->pids[i]);
1048                 }
1049                 url_fseek(pb, pos, SEEK_SET);
1050                 mpegts_scan_pat(ts);
1051                 
1052                 handle_packets(ts, MAX_SCAN_PACKETS);
1053             }
1054             
1055             if (ts->nb_services <= 0)
1056                 return -1;
1057             
1058             /* tune to first service found */
1059             service = ts->services[0];
1060             sid = service->sid;
1061 #ifdef DEBUG_SI
1062             printf("tuning to '%s'\n", service->name);
1063 #endif
1064             
1065             /* now find the info for the first service if we found any,
1066                otherwise try to filter all PATs */
1067             
1068             url_fseek(pb, pos, SEEK_SET);
1069             mpegts_set_service(ts, sid, set_service_cb, ts);
1070             
1071             handle_packets(ts, MAX_SCAN_PACKETS);
1072             
1073             /* if could not find service, exit */
1074             if (ts->set_service_ret != 0)
1075                 return -1;
1076             
1077 #ifdef DEBUG_SI
1078             printf("tuning done\n");
1079 #endif
1080         }
1081         s->ctx_flags |= AVFMTCTX_NOHEADER;
1082     } else {
1083         AVStream *st;
1084         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1085         int64_t pcrs[2], pcr_h;
1086         int packet_count[2];
1087         uint8_t packet[TS_PACKET_SIZE];
1088         
1089         /* only read packets */
1090
1091         s->pts_num = 1;
1092         s->pts_den = 27000000;
1093         
1094         st = av_new_stream(s, 0);
1095         if (!st)
1096             goto fail;
1097         st->codec.codec_type = CODEC_TYPE_DATA;
1098         st->codec.codec_id = CODEC_ID_MPEG2TS;
1099         
1100         /* we iterate until we find two PCRs to estimate the bitrate */
1101         pcr_pid = -1;
1102         nb_pcrs = 0;
1103         nb_packets = 0;
1104         for(;;) {
1105             ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1106             if (ret < 0)
1107                 return -1;
1108             pid = ((packet[1] & 0x1f) << 8) | packet[2];
1109             if ((pcr_pid == -1 || pcr_pid == pid) &&
1110                 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1111                 pcr_pid = pid;
1112                 packet_count[nb_pcrs] = nb_packets;
1113                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1114                 nb_pcrs++;
1115                 if (nb_pcrs >= 2)
1116                     break;
1117             }
1118             nb_packets++;
1119         }
1120
1121         /* NOTE1: the bitrate is computed without the FEC */
1122         /* NOTE2: it is only the bitrate of the start of the stream */
1123         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1124         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1125         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1126         st->codec.bit_rate = s->bit_rate;
1127         st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
1128 #if 0
1129         printf("start=%0.3f pcr=%0.3f incr=%d\n",
1130                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1131 #endif
1132     }
1133
1134     url_fseek(pb, pos, SEEK_SET);
1135     return 0;
1136  fail:
1137     return -1;
1138 }
1139
1140 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1141
1142 static int mpegts_raw_read_packet(AVFormatContext *s,
1143                                   AVPacket *pkt)
1144 {
1145     MpegTSContext *ts = s->priv_data;
1146     int ret, i;
1147     int64_t pcr_h, next_pcr_h, pos;
1148     int pcr_l, next_pcr_l;
1149     uint8_t pcr_buf[12];
1150
1151     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1152         return -ENOMEM;
1153     ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1154     if (ret < 0) {
1155         av_free_packet(pkt);
1156         return ret;
1157     }
1158     if (ts->mpeg2ts_compute_pcr) {
1159         /* compute exact PCR for each packet */
1160         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1161             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1162             pos = url_ftell(&s->pb);
1163             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1164                 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1165                 get_buffer(&s->pb, pcr_buf, 12);
1166                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1167                     /* XXX: not precise enough */
1168                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) / 
1169                         (i + 1);
1170                     break;
1171                 }
1172             }
1173             url_fseek(&s->pb, pos, SEEK_SET);
1174             /* no next PCR found: we use previous increment */
1175             ts->cur_pcr = pcr_h * 300 + pcr_l;
1176         }
1177         pkt->pts = ts->cur_pcr;
1178         pkt->duration = ts->pcr_incr;
1179         ts->cur_pcr += ts->pcr_incr;
1180     }
1181     pkt->stream_index = 0;
1182     return 0;
1183 }
1184
1185 static int mpegts_read_packet(AVFormatContext *s,
1186                               AVPacket *pkt)
1187 {
1188     MpegTSContext *ts = s->priv_data;
1189
1190     if (!ts->mpeg2ts_raw) {
1191         ts->pkt = pkt;
1192         return handle_packets(ts, 0);
1193     } else {
1194         return mpegts_raw_read_packet(s, pkt);
1195     }
1196 }
1197
1198 static int mpegts_read_close(AVFormatContext *s)
1199 {
1200     MpegTSContext *ts = s->priv_data;
1201     int i;
1202     for(i=0;i<NB_PID_MAX;i++)
1203         av_free(ts->pids[i]);
1204     return 0;
1205 }
1206
1207 /**************************************************************/
1208 /* parsing functions - called from other demuxers such as RTP */
1209
1210 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1211 {
1212     MpegTSContext *ts;
1213     
1214     ts = av_mallocz(sizeof(MpegTSContext));
1215     if (!ts)
1216         return NULL;
1217     /* no stream case, currently used by RTP */
1218     ts->raw_packet_size = TS_PACKET_SIZE;
1219     ts->stream = s;
1220     ts->auto_guess = 1;
1221     return ts;
1222 }
1223
1224 /* return the consumed length if a packet was output, or -1 if no
1225    packet is output */
1226 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1227                         const uint8_t *buf, int len)
1228 {
1229     int len1;
1230
1231     len1 = len;
1232     ts->pkt = pkt;
1233     ts->stop_parse = 0;
1234     for(;;) {
1235         if (ts->stop_parse)
1236             break;
1237         if (len < TS_PACKET_SIZE)
1238             return -1;
1239         if (buf[0] != 0x47) {
1240             buf--;
1241             len--;
1242         } else {
1243             handle_packet(ts, buf);
1244             buf += TS_PACKET_SIZE;
1245             len -= TS_PACKET_SIZE;
1246         }
1247     }
1248     return len1 - len;
1249 }
1250
1251 void mpegts_parse_close(MpegTSContext *ts)
1252 {
1253     int i;
1254
1255     for(i=0;i<NB_PID_MAX;i++)
1256         av_free(ts->pids[i]);
1257     av_free(ts);
1258 }
1259
1260 AVInputFormat mpegts_demux = {
1261     "mpegts",
1262     "MPEG2 transport stream format",
1263     sizeof(MpegTSContext),
1264     mpegts_probe,
1265     mpegts_read_header,
1266     mpegts_read_packet,
1267     mpegts_read_close,
1268     .flags = AVFMT_SHOW_IDS,
1269 };
1270
1271 int mpegts_init(void)
1272 {
1273     av_register_input_format(&mpegts_demux);
1274 #ifdef CONFIG_ENCODERS
1275     av_register_output_format(&mpegts_mux);
1276 #endif
1277     return 0;
1278 }