Add Bluray Subtitle Support
[libav.git] / libavformat / mpegts.c
1 /*
2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 //#define DEBUG
23 //#define DEBUG_SEEK
24
25 #include "libavutil/crc.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavcodec/bytestream.h"
28 #include "avformat.h"
29 #include "mpegts.h"
30 #include "internal.h"
31 #include "seek.h"
32
33 /* 1.0 second at 24Mbit/s */
34 #define MAX_SCAN_PACKETS 32000
35
36 /* maximum size in which we look for synchronisation if
37 synchronisation is lost */
38 #define MAX_RESYNC_SIZE 4096
39
40 #define MAX_PES_PAYLOAD 200*1024
41
42 typedef struct PESContext PESContext;
43
44 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
45
46 enum MpegTSFilterType {
47 MPEGTS_PES,
48 MPEGTS_SECTION,
49 };
50
51 typedef struct MpegTSFilter MpegTSFilter;
52
53 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
54
55 typedef struct MpegTSPESFilter {
56 PESCallback *pes_cb;
57 void *opaque;
58 } MpegTSPESFilter;
59
60 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
61
62 typedef void SetServiceCallback(void *opaque, int ret);
63
64 typedef struct MpegTSSectionFilter {
65 int section_index;
66 int section_h_size;
67 uint8_t *section_buf;
68 unsigned int check_crc:1;
69 unsigned int end_of_section_reached:1;
70 SectionCallback *section_cb;
71 void *opaque;
72 } MpegTSSectionFilter;
73
74 struct MpegTSFilter {
75 int pid;
76 int last_cc; /* last cc code (-1 if first packet) */
77 enum MpegTSFilterType type;
78 union {
79 MpegTSPESFilter pes_filter;
80 MpegTSSectionFilter section_filter;
81 } u;
82 };
83
84 #define MAX_PIDS_PER_PROGRAM 64
85 struct Program {
86 unsigned int id; //program id/service id
87 unsigned int nb_pids;
88 unsigned int pids[MAX_PIDS_PER_PROGRAM];
89 };
90
91 struct MpegTSContext {
92 /* user data */
93 AVFormatContext *stream;
94 /** raw packet size, including FEC if present */
95 int raw_packet_size;
96
97 int pos47;
98
99 /** if true, all pids are analyzed to find streams */
100 int auto_guess;
101
102 /** compute exact PCR for each transport stream packet */
103 int mpeg2ts_compute_pcr;
104
105 int64_t cur_pcr; /**< used to estimate the exact PCR */
106 int pcr_incr; /**< used to estimate the exact PCR */
107
108 /* data needed to handle file based ts */
109 /** stop parsing loop */
110 int stop_parse;
111 /** packet containing Audio/Video data */
112 AVPacket *pkt;
113 /** to detect seek */
114 int64_t last_pos;
115
116 /******************************************/
117 /* private mpegts data */
118 /* scan context */
119 /** structure to keep track of Program->pids mapping */
120 unsigned int nb_prg;
121 struct Program *prg;
122
123
124 /** filters for various streams specified by PMT + for the PAT and PMT */
125 MpegTSFilter *pids[NB_PID_MAX];
126 };
127
128 /* TS stream handling */
129
130 enum MpegTSState {
131 MPEGTS_HEADER = 0,
132 MPEGTS_PESHEADER,
133 MPEGTS_PESHEADER_FILL,
134 MPEGTS_PAYLOAD,
135 MPEGTS_SKIP,
136 };
137
138 /* enough for PES header + length */
139 #define PES_START_SIZE 6
140 #define PES_HEADER_SIZE 9
141 #define MAX_PES_HEADER_SIZE (9 + 255)
142
143 struct PESContext {
144 int pid;
145 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
146 int stream_type;
147 MpegTSContext *ts;
148 AVFormatContext *stream;
149 AVStream *st;
150 enum MpegTSState state;
151 /* used to get the format */
152 int data_index;
153 int total_size;
154 int pes_header_size;
155 int64_t pts, dts;
156 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
157 uint8_t header[MAX_PES_HEADER_SIZE];
158 uint8_t *buffer;
159 };
160
161 extern AVInputFormat mpegts_demuxer;
162
163 static void clear_program(MpegTSContext *ts, unsigned int programid)
164 {
165 int i;
166
167 for(i=0; i<ts->nb_prg; i++)
168 if(ts->prg[i].id == programid)
169 ts->prg[i].nb_pids = 0;
170 }
171
172 static void clear_programs(MpegTSContext *ts)
173 {
174 av_freep(&ts->prg);
175 ts->nb_prg=0;
176 }
177
178 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
179 {
180 struct Program *p;
181 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
182 if(!tmp)
183 return;
184 ts->prg = tmp;
185 p = &ts->prg[ts->nb_prg];
186 p->id = programid;
187 p->nb_pids = 0;
188 ts->nb_prg++;
189 }
190
191 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
192 {
193 int i;
194 struct Program *p = NULL;
195 for(i=0; i<ts->nb_prg; i++) {
196 if(ts->prg[i].id == programid) {
197 p = &ts->prg[i];
198 break;
199 }
200 }
201 if(!p)
202 return;
203
204 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
205 return;
206 p->pids[p->nb_pids++] = pid;
207 }
208
209 /**
210 * \brief discard_pid() decides if the pid is to be discarded according
211 * to caller's programs selection
212 * \param ts : - TS context
213 * \param pid : - pid
214 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
215 * 0 otherwise
216 */
217 static int discard_pid(MpegTSContext *ts, unsigned int pid)
218 {
219 int i, j, k;
220 int used = 0, discarded = 0;
221 struct Program *p;
222 for(i=0; i<ts->nb_prg; i++) {
223 p = &ts->prg[i];
224 for(j=0; j<p->nb_pids; j++) {
225 if(p->pids[j] != pid)
226 continue;
227 //is program with id p->id set to be discarded?
228 for(k=0; k<ts->stream->nb_programs; k++) {
229 if(ts->stream->programs[k]->id == p->id) {
230 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
231 discarded++;
232 else
233 used++;
234 }
235 }
236 }
237 }
238
239 return !used && discarded;
240 }
241
242 /**
243 * Assembles PES packets out of TS packets, and then calls the "section_cb"
244 * function when they are complete.
245 */
246 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
247 const uint8_t *buf, int buf_size, int is_start)
248 {
249 MpegTSSectionFilter *tss = &tss1->u.section_filter;
250 int len;
251
252 if (is_start) {
253 memcpy(tss->section_buf, buf, buf_size);
254 tss->section_index = buf_size;
255 tss->section_h_size = -1;
256 tss->end_of_section_reached = 0;
257 } else {
258 if (tss->end_of_section_reached)
259 return;
260 len = 4096 - tss->section_index;
261 if (buf_size < len)
262 len = buf_size;
263 memcpy(tss->section_buf + tss->section_index, buf, len);
264 tss->section_index += len;
265 }
266
267 /* compute section length if possible */
268 if (tss->section_h_size == -1 && tss->section_index >= 3) {
269 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
270 if (len > 4096)
271 return;
272 tss->section_h_size = len;
273 }
274
275 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
276 tss->end_of_section_reached = 1;
277 if (!tss->check_crc ||
278 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
279 tss->section_buf, tss->section_h_size) == 0)
280 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
281 }
282 }
283
284 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
285 SectionCallback *section_cb, void *opaque,
286 int check_crc)
287
288 {
289 MpegTSFilter *filter;
290 MpegTSSectionFilter *sec;
291
292 dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
293
294 if (pid >= NB_PID_MAX || ts->pids[pid])
295 return NULL;
296 filter = av_mallocz(sizeof(MpegTSFilter));
297 if (!filter)
298 return NULL;
299 ts->pids[pid] = filter;
300 filter->type = MPEGTS_SECTION;
301 filter->pid = pid;
302 filter->last_cc = -1;
303 sec = &filter->u.section_filter;
304 sec->section_cb = section_cb;
305 sec->opaque = opaque;
306 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
307 sec->check_crc = check_crc;
308 if (!sec->section_buf) {
309 av_free(filter);
310 return NULL;
311 }
312 return filter;
313 }
314
315 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
316 PESCallback *pes_cb,
317 void *opaque)
318 {
319 MpegTSFilter *filter;
320 MpegTSPESFilter *pes;
321
322 if (pid >= NB_PID_MAX || ts->pids[pid])
323 return NULL;
324 filter = av_mallocz(sizeof(MpegTSFilter));
325 if (!filter)
326 return NULL;
327 ts->pids[pid] = filter;
328 filter->type = MPEGTS_PES;
329 filter->pid = pid;
330 filter->last_cc = -1;
331 pes = &filter->u.pes_filter;
332 pes->pes_cb = pes_cb;
333 pes->opaque = opaque;
334 return filter;
335 }
336
337 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
338 {
339 int pid;
340
341 pid = filter->pid;
342 if (filter->type == MPEGTS_SECTION)
343 av_freep(&filter->u.section_filter.section_buf);
344 else if (filter->type == MPEGTS_PES) {
345 PESContext *pes = filter->u.pes_filter.opaque;
346 av_freep(&pes->buffer);
347 /* referenced private data will be freed later in
348 * av_close_input_stream */
349 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
350 av_freep(&filter->u.pes_filter.opaque);
351 }
352 }
353
354 av_free(filter);
355 ts->pids[pid] = NULL;
356 }
357
358 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
359 int stat[TS_MAX_PACKET_SIZE];
360 int i;
361 int x=0;
362 int best_score=0;
363
364 memset(stat, 0, packet_size*sizeof(int));
365
366 for(x=i=0; i<size-3; i++){
367 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
368 stat[x]++;
369 if(stat[x] > best_score){
370 best_score= stat[x];
371 if(index) *index= x;
372 }
373 }
374
375 x++;
376 if(x == packet_size) x= 0;
377 }
378
379 return best_score;
380 }
381
382 /* autodetect fec presence. Must have at least 1024 bytes */
383 static int get_packet_size(const uint8_t *buf, int size)
384 {
385 int score, fec_score, dvhs_score;
386
387 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
388 return -1;
389
390 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
391 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
392 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
393 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
394
395 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
396 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
397 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
398 else return -1;
399 }
400
401 typedef struct SectionHeader {
402 uint8_t tid;
403 uint16_t id;
404 uint8_t version;
405 uint8_t sec_num;
406 uint8_t last_sec_num;
407 } SectionHeader;
408
409 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
410 {
411 const uint8_t *p;
412 int c;
413
414 p = *pp;
415 if (p >= p_end)
416 return -1;
417 c = *p++;
418 *pp = p;
419 return c;
420 }
421
422 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
423 {
424 const uint8_t *p;
425 int c;
426
427 p = *pp;
428 if ((p + 1) >= p_end)
429 return -1;
430 c = AV_RB16(p);
431 p += 2;
432 *pp = p;
433 return c;
434 }
435
436 /* read and allocate a DVB string preceeded by its length */
437 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
438 {
439 int len;
440 const uint8_t *p;
441 char *str;
442
443 p = *pp;
444 len = get8(&p, p_end);
445 if (len < 0)
446 return NULL;
447 if ((p + len) > p_end)
448 return NULL;
449 str = av_malloc(len + 1);
450 if (!str)
451 return NULL;
452 memcpy(str, p, len);
453 str[len] = '\0';
454 p += len;
455 *pp = p;
456 return str;
457 }
458
459 static int parse_section_header(SectionHeader *h,
460 const uint8_t **pp, const uint8_t *p_end)
461 {
462 int val;
463
464 val = get8(pp, p_end);
465 if (val < 0)
466 return -1;
467 h->tid = val;
468 *pp += 2;
469 val = get16(pp, p_end);
470 if (val < 0)
471 return -1;
472 h->id = val;
473 val = get8(pp, p_end);
474 if (val < 0)
475 return -1;
476 h->version = (val >> 1) & 0x1f;
477 val = get8(pp, p_end);
478 if (val < 0)
479 return -1;
480 h->sec_num = val;
481 val = get8(pp, p_end);
482 if (val < 0)
483 return -1;
484 h->last_sec_num = val;
485 return 0;
486 }
487
488 typedef struct {
489 uint32_t stream_type;
490 enum CodecType codec_type;
491 enum CodecID codec_id;
492 } StreamType;
493
494 static const StreamType ISO_types[] = {
495 { 0x01, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
496 { 0x02, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
497 { 0x03, CODEC_TYPE_AUDIO, CODEC_ID_MP3 },
498 { 0x04, CODEC_TYPE_AUDIO, CODEC_ID_MP3 },
499 { 0x0f, CODEC_TYPE_AUDIO, CODEC_ID_AAC },
500 { 0x10, CODEC_TYPE_VIDEO, CODEC_ID_MPEG4 },
501 { 0x1b, CODEC_TYPE_VIDEO, CODEC_ID_H264 },
502 { 0xd1, CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
503 { 0xea, CODEC_TYPE_VIDEO, CODEC_ID_VC1 },
504 { 0 },
505 };
506
507 static const StreamType HDMV_types[] = {
508 { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
509 { 0x82, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
510 { 0x90, CODEC_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
511 { 0 },
512 };
513
514 /* ATSC ? */
515 static const StreamType MISC_types[] = {
516 { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
517 { 0x8a, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
518 { 0 },
519 };
520
521 static const StreamType REGD_types[] = {
522 { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
523 { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
524 { 0 },
525 };
526
527 /* descriptor present */
528 static const StreamType DESC_types[] = {
529 { 0x6a, CODEC_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
530 { 0x7a, CODEC_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
531 { 0x7b, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
532 { 0x59, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
533 { 0 },
534 };
535
536 static void mpegts_find_stream_type(AVStream *st,
537 uint32_t stream_type, const StreamType *types)
538 {
539 for (; types->stream_type; types++) {
540 if (stream_type == types->stream_type) {
541 st->codec->codec_type = types->codec_type;
542 st->codec->codec_id = types->codec_id;
543 return;
544 }
545 }
546 }
547
548 static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)
549 {
550 AVStream *st = av_new_stream(pes->stream, pes->pid);
551
552 if (!st)
553 return NULL;
554
555 av_set_pts_info(st, 33, 1, 90000);
556 st->priv_data = pes;
557 st->codec->codec_type = CODEC_TYPE_DATA;
558 st->codec->codec_id = CODEC_ID_NONE;
559 st->need_parsing = AVSTREAM_PARSE_FULL;
560 pes->st = st;
561
562 dprintf(pes->stream, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",
563 pes->stream_type, pes->pid, (char*)&prog_reg_desc);
564
565 st->codec->codec_tag = pes->stream_type;
566
567 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
568 if (prog_reg_desc == AV_RL32("HDMV") &&
569 st->codec->codec_id == CODEC_ID_NONE)
570 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
571 if (st->codec->codec_id == CODEC_ID_NONE)
572 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
573
574 /* stream was not present in PMT, guess based on PES start code */
575 if (st->codec->codec_id == CODEC_ID_NONE) {
576 if (code >= 0x1c0 && code <= 0x1df) {
577 st->codec->codec_type = CODEC_TYPE_AUDIO;
578 st->codec->codec_id = CODEC_ID_MP2;
579 } else if (code == 0x1bd) {
580 st->codec->codec_type = CODEC_TYPE_AUDIO;
581 st->codec->codec_id = CODEC_ID_AC3;
582 }
583 }
584
585 return st;
586 }
587
588 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
589 {
590 MpegTSContext *ts = filter->u.section_filter.opaque;
591 SectionHeader h1, *h = &h1;
592 PESContext *pes;
593 AVStream *st;
594 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
595 int program_info_length, pcr_pid, pid, stream_type;
596 int desc_list_len, desc_len, desc_tag;
597 int comp_page, anc_page;
598 char language[4];
599 uint32_t prog_reg_desc = 0; /* registration descriptor */
600
601 #ifdef DEBUG
602 dprintf(ts->stream, "PMT: len %i\n", section_len);
603 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
604 #endif
605
606 p_end = section + section_len - 4;
607 p = section;
608 if (parse_section_header(h, &p, p_end) < 0)
609 return;
610
611 dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
612 h->id, h->sec_num, h->last_sec_num);
613
614 if (h->tid != PMT_TID)
615 return;
616
617 clear_program(ts, h->id);
618 pcr_pid = get16(&p, p_end) & 0x1fff;
619 if (pcr_pid < 0)
620 return;
621 add_pid_to_pmt(ts, h->id, pcr_pid);
622
623 dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
624
625 program_info_length = get16(&p, p_end) & 0xfff;
626 if (program_info_length < 0)
627 return;
628 while(program_info_length >= 2) {
629 uint8_t tag, len;
630 tag = get8(&p, p_end);
631 len = get8(&p, p_end);
632 if(len > program_info_length - 2)
633 //something else is broken, exit the program_descriptors_loop
634 break;
635 program_info_length -= len + 2;
636 if(tag == 0x05 && len >= 4) { // registration descriptor
637 prog_reg_desc = bytestream_get_le32(&p);
638 len -= 4;
639 }
640 p += len;
641 }
642 p += program_info_length;
643 if (p >= p_end)
644 return;
645
646 // stop parsing after pmt, we found header
647 if (!ts->stream->nb_streams)
648 ts->stop_parse = 1;
649
650 for(;;) {
651 st = 0;
652 stream_type = get8(&p, p_end);
653 if (stream_type < 0)
654 break;
655 pid = get16(&p, p_end) & 0x1fff;
656 if (pid < 0)
657 break;
658
659 /* now create ffmpeg stream */
660 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
661 pes = ts->pids[pid]->u.pes_filter.opaque;
662 st = pes->st;
663 } else {
664 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
665 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
666 if (pes)
667 st = new_pes_av_stream(pes, prog_reg_desc, 0);
668 }
669
670 if (!st)
671 return;
672
673 add_pid_to_pmt(ts, h->id, pid);
674
675 av_program_add_stream_index(ts->stream, h->id, st->index);
676
677 desc_list_len = get16(&p, p_end) & 0xfff;
678 if (desc_list_len < 0)
679 break;
680 desc_list_end = p + desc_list_len;
681 if (desc_list_end > p_end)
682 break;
683 for(;;) {
684 desc_tag = get8(&p, desc_list_end);
685 if (desc_tag < 0)
686 break;
687 desc_len = get8(&p, desc_list_end);
688 if (desc_len < 0)
689 break;
690 desc_end = p + desc_len;
691 if (desc_end > desc_list_end)
692 break;
693
694 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
695 desc_tag, desc_len);
696
697 if (st->codec->codec_id == CODEC_ID_NONE &&
698 stream_type == STREAM_TYPE_PRIVATE_DATA)
699 mpegts_find_stream_type(st, desc_tag, DESC_types);
700
701 switch(desc_tag) {
702 case 0x59: /* subtitling descriptor */
703 language[0] = get8(&p, desc_end);
704 language[1] = get8(&p, desc_end);
705 language[2] = get8(&p, desc_end);
706 language[3] = 0;
707 get8(&p, desc_end);
708 comp_page = get16(&p, desc_end);
709 anc_page = get16(&p, desc_end);
710 st->codec->sub_id = (anc_page << 16) | comp_page;
711 av_metadata_set(&st->metadata, "language", language);
712 break;
713 case 0x0a: /* ISO 639 language descriptor */
714 language[0] = get8(&p, desc_end);
715 language[1] = get8(&p, desc_end);
716 language[2] = get8(&p, desc_end);
717 language[3] = 0;
718 av_metadata_set(&st->metadata, "language", language);
719 break;
720 case 0x05: /* registration descriptor */
721 st->codec->codec_tag = bytestream_get_le32(&p);
722 dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
723 if (st->codec->codec_id == CODEC_ID_NONE &&
724 stream_type == STREAM_TYPE_PRIVATE_DATA)
725 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
726 break;
727 default:
728 break;
729 }
730 p = desc_end;
731 }
732 p = desc_list_end;
733 }
734 /* all parameters are there */
735 mpegts_close_filter(ts, filter);
736 }
737
738 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
739 {
740 MpegTSContext *ts = filter->u.section_filter.opaque;
741 SectionHeader h1, *h = &h1;
742 const uint8_t *p, *p_end;
743 int sid, pmt_pid;
744
745 #ifdef DEBUG
746 dprintf(ts->stream, "PAT:\n");
747 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
748 #endif
749 p_end = section + section_len - 4;
750 p = section;
751 if (parse_section_header(h, &p, p_end) < 0)
752 return;
753 if (h->tid != PAT_TID)
754 return;
755
756 clear_programs(ts);
757 for(;;) {
758 sid = get16(&p, p_end);
759 if (sid < 0)
760 break;
761 pmt_pid = get16(&p, p_end) & 0x1fff;
762 if (pmt_pid < 0)
763 break;
764
765 dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
766
767 if (sid == 0x0000) {
768 /* NIT info */
769 } else {
770 av_new_program(ts->stream, sid);
771 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
772 add_pat_entry(ts, sid);
773 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
774 add_pid_to_pmt(ts, sid, pmt_pid);
775 }
776 }
777 }
778
779 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
780 {
781 MpegTSContext *ts = filter->u.section_filter.opaque;
782 SectionHeader h1, *h = &h1;
783 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
784 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
785 char *name, *provider_name;
786
787 #ifdef DEBUG
788 dprintf(ts->stream, "SDT:\n");
789 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
790 #endif
791
792 p_end = section + section_len - 4;
793 p = section;
794 if (parse_section_header(h, &p, p_end) < 0)
795 return;
796 if (h->tid != SDT_TID)
797 return;
798 onid = get16(&p, p_end);
799 if (onid < 0)
800 return;
801 val = get8(&p, p_end);
802 if (val < 0)
803 return;
804 for(;;) {
805 sid = get16(&p, p_end);
806 if (sid < 0)
807 break;
808 val = get8(&p, p_end);
809 if (val < 0)
810 break;
811 desc_list_len = get16(&p, p_end) & 0xfff;
812 if (desc_list_len < 0)
813 break;
814 desc_list_end = p + desc_list_len;
815 if (desc_list_end > p_end)
816 break;
817 for(;;) {
818 desc_tag = get8(&p, desc_list_end);
819 if (desc_tag < 0)
820 break;
821 desc_len = get8(&p, desc_list_end);
822 desc_end = p + desc_len;
823 if (desc_end > desc_list_end)
824 break;
825
826 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
827 desc_tag, desc_len);
828
829 switch(desc_tag) {
830 case 0x48:
831 service_type = get8(&p, p_end);
832 if (service_type < 0)
833 break;
834 provider_name = getstr8(&p, p_end);
835 if (!provider_name)
836 break;
837 name = getstr8(&p, p_end);
838 if (name) {
839 AVProgram *program = av_new_program(ts->stream, sid);
840 if(program) {
841 av_metadata_set(&program->metadata, "name", name);
842 av_metadata_set(&program->metadata, "provider_name", provider_name);
843 }
844 }
845 av_free(name);
846 av_free(provider_name);
847 break;
848 default:
849 break;
850 }
851 p = desc_end;
852 }
853 p = desc_list_end;
854 }
855 }
856
857 static int64_t get_pts(const uint8_t *p)
858 {
859 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
860 pts |= (AV_RB16(p + 1) >> 1) << 15;
861 pts |= AV_RB16(p + 3) >> 1;
862 return pts;
863 }
864
865 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
866 {
867 av_init_packet(pkt);
868
869 pkt->destruct = av_destruct_packet;
870 pkt->data = pes->buffer;
871 pkt->size = pes->data_index;
872 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
873
874 pkt->stream_index = pes->st->index;
875 pkt->pts = pes->pts;
876 pkt->dts = pes->dts;
877 /* store position of first TS packet of this PES packet */
878 pkt->pos = pes->ts_packet_pos;
879
880 /* reset pts values */
881 pes->pts = AV_NOPTS_VALUE;
882 pes->dts = AV_NOPTS_VALUE;
883 pes->buffer = NULL;
884 pes->data_index = 0;
885 }
886
887 /* return non zero if a packet could be constructed */
888 static int mpegts_push_data(MpegTSFilter *filter,
889 const uint8_t *buf, int buf_size, int is_start,
890 int64_t pos)
891 {
892 PESContext *pes = filter->u.pes_filter.opaque;
893 MpegTSContext *ts = pes->ts;
894 const uint8_t *p;
895 int len, code;
896
897 if(!ts->pkt)
898 return 0;
899
900 if (is_start) {
901 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
902 new_pes_packet(pes, ts->pkt);
903 ts->stop_parse = 1;
904 }
905 pes->state = MPEGTS_HEADER;
906 pes->data_index = 0;
907 pes->ts_packet_pos = pos;
908 }
909 p = buf;
910 while (buf_size > 0) {
911 switch(pes->state) {
912 case MPEGTS_HEADER:
913 len = PES_START_SIZE - pes->data_index;
914 if (len > buf_size)
915 len = buf_size;
916 memcpy(pes->header + pes->data_index, p, len);
917 pes->data_index += len;
918 p += len;
919 buf_size -= len;
920 if (pes->data_index == PES_START_SIZE) {
921 /* we got all the PES or section header. We can now
922 decide */
923 #if 0
924 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
925 #endif
926 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
927 pes->header[2] == 0x01) {
928 /* it must be an mpeg2 PES stream */
929 code = pes->header[3] | 0x100;
930 dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
931
932 if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
933 (pes->st && pes->st->discard == AVDISCARD_ALL) ||
934 code == 0x1be) /* padding_stream */
935 goto skip;
936
937 /* stream not present in PMT */
938 if (!pes->st)
939 pes->st = new_pes_av_stream(pes, 0, code);
940 if (!pes->st)
941 return AVERROR(ENOMEM);
942
943 pes->total_size = AV_RB16(pes->header + 4);
944 /* NOTE: a zero total size means the PES size is
945 unbounded */
946 if (!pes->total_size)
947 pes->total_size = MAX_PES_PAYLOAD;
948
949 /* allocate pes buffer */
950 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
951 if (!pes->buffer)
952 return AVERROR(ENOMEM);
953
954 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
955 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
956 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
957 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
958 pes->state = MPEGTS_PESHEADER;
959 if (pes->st->codec->codec_id == CODEC_ID_NONE) {
960 dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
961 pes->pid, pes->stream_type);
962 pes->st->codec->codec_id = CODEC_ID_PROBE;
963 }
964 } else {
965 pes->state = MPEGTS_PAYLOAD;
966 pes->data_index = 0;
967 }
968 } else {
969 /* otherwise, it should be a table */
970 /* skip packet */
971 skip:
972 pes->state = MPEGTS_SKIP;
973 continue;
974 }
975 }
976 break;
977 /**********************************************/
978 /* PES packing parsing */
979 case MPEGTS_PESHEADER:
980 len = PES_HEADER_SIZE - pes->data_index;
981 if (len < 0)
982 return -1;
983 if (len > buf_size)
984 len = buf_size;
985 memcpy(pes->header + pes->data_index, p, len);
986 pes->data_index += len;
987 p += len;
988 buf_size -= len;
989 if (pes->data_index == PES_HEADER_SIZE) {
990 pes->pes_header_size = pes->header[8] + 9;
991 pes->state = MPEGTS_PESHEADER_FILL;
992 }
993 break;
994 case MPEGTS_PESHEADER_FILL:
995 len = pes->pes_header_size - pes->data_index;
996 if (len < 0)
997 return -1;
998 if (len > buf_size)
999 len = buf_size;
1000 memcpy(pes->header + pes->data_index, p, len);
1001 pes->data_index += len;
1002 p += len;
1003 buf_size -= len;
1004 if (pes->data_index == pes->pes_header_size) {
1005 const uint8_t *r;
1006 unsigned int flags;
1007
1008 flags = pes->header[7];
1009 r = pes->header + 9;
1010 pes->pts = AV_NOPTS_VALUE;
1011 pes->dts = AV_NOPTS_VALUE;
1012 if ((flags & 0xc0) == 0x80) {
1013 pes->dts = pes->pts = get_pts(r);
1014 r += 5;
1015 } else if ((flags & 0xc0) == 0xc0) {
1016 pes->pts = get_pts(r);
1017 r += 5;
1018 pes->dts = get_pts(r);
1019 r += 5;
1020 }
1021
1022 /* we got the full header. We parse it and get the payload */
1023 pes->state = MPEGTS_PAYLOAD;
1024 pes->data_index = 0;
1025 }
1026 break;
1027 case MPEGTS_PAYLOAD:
1028 if (buf_size > 0) {
1029 if (pes->data_index+buf_size > pes->total_size) {
1030 new_pes_packet(pes, ts->pkt);
1031 pes->total_size = MAX_PES_PAYLOAD;
1032 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
1033 if (!pes->buffer)
1034 return AVERROR(ENOMEM);
1035 ts->stop_parse = 1;
1036 }
1037 memcpy(pes->buffer+pes->data_index, p, buf_size);
1038 pes->data_index += buf_size;
1039 }
1040 buf_size = 0;
1041 break;
1042 case MPEGTS_SKIP:
1043 buf_size = 0;
1044 break;
1045 }
1046 }
1047
1048 return 0;
1049 }
1050
1051 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1052 {
1053 MpegTSFilter *tss;
1054 PESContext *pes;
1055
1056 /* if no pid found, then add a pid context */
1057 pes = av_mallocz(sizeof(PESContext));
1058 if (!pes)
1059 return 0;
1060 pes->ts = ts;
1061 pes->stream = ts->stream;
1062 pes->pid = pid;
1063 pes->pcr_pid = pcr_pid;
1064 pes->stream_type = stream_type;
1065 pes->state = MPEGTS_SKIP;
1066 pes->pts = AV_NOPTS_VALUE;
1067 pes->dts = AV_NOPTS_VALUE;
1068 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1069 if (!tss) {
1070 av_free(pes);
1071 return 0;
1072 }
1073 return pes;
1074 }
1075
1076 /* handle one TS packet */
1077 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1078 {
1079 AVFormatContext *s = ts->stream;
1080 MpegTSFilter *tss;
1081 int len, pid, cc, cc_ok, afc, is_start;
1082 const uint8_t *p, *p_end;
1083 int64_t pos;
1084
1085 pid = AV_RB16(packet + 1) & 0x1fff;
1086 if(pid && discard_pid(ts, pid))
1087 return 0;
1088 is_start = packet[1] & 0x40;
1089 tss = ts->pids[pid];
1090 if (ts->auto_guess && tss == NULL && is_start) {
1091 add_pes_stream(ts, pid, -1, 0);
1092 tss = ts->pids[pid];
1093 }
1094 if (!tss)
1095 return 0;
1096
1097 /* continuity check (currently not used) */
1098 cc = (packet[3] & 0xf);
1099 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1100 tss->last_cc = cc;
1101
1102 /* skip adaptation field */
1103 afc = (packet[3] >> 4) & 3;
1104 p = packet + 4;
1105 if (afc == 0) /* reserved value */
1106 return 0;
1107 if (afc == 2) /* adaptation field only */
1108 return 0;
1109 if (afc == 3) {
1110 /* skip adapation field */
1111 p += p[0] + 1;
1112 }
1113 /* if past the end of packet, ignore */
1114 p_end = packet + TS_PACKET_SIZE;
1115 if (p >= p_end)
1116 return 0;
1117
1118 pos = url_ftell(ts->stream->pb);
1119 ts->pos47= pos % ts->raw_packet_size;
1120
1121 if (tss->type == MPEGTS_SECTION) {
1122 if (is_start) {
1123 /* pointer field present */
1124 len = *p++;
1125 if (p + len > p_end)
1126 return 0;
1127 if (len && cc_ok) {
1128 /* write remaining section bytes */
1129 write_section_data(s, tss,
1130 p, len, 0);
1131 /* check whether filter has been closed */
1132 if (!ts->pids[pid])
1133 return 0;
1134 }
1135 p += len;
1136 if (p < p_end) {
1137 write_section_data(s, tss,
1138 p, p_end - p, 1);
1139 }
1140 } else {
1141 if (cc_ok) {
1142 write_section_data(s, tss,
1143 p, p_end - p, 0);
1144 }
1145 }
1146 } else {
1147 int ret;
1148 // Note: The position here points actually behind the current packet.
1149 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1150 pos - ts->raw_packet_size)) < 0)
1151 return ret;
1152 }
1153
1154 return 0;
1155 }
1156
1157 /* XXX: try to find a better synchro over several packets (use
1158 get_packet_size() ?) */
1159 static int mpegts_resync(ByteIOContext *pb)
1160 {
1161 int c, i;
1162
1163 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1164 c = url_fgetc(pb);
1165 if (c < 0)
1166 return -1;
1167 if (c == 0x47) {
1168 url_fseek(pb, -1, SEEK_CUR);
1169 return 0;
1170 }
1171 }
1172 /* no sync found */
1173 return -1;
1174 }
1175
1176 /* return -1 if error or EOF. Return 0 if OK. */
1177 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1178 {
1179 int skip, len;
1180
1181 for(;;) {
1182 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1183 if (len != TS_PACKET_SIZE)
1184 return AVERROR(EIO);
1185 /* check paquet sync byte */
1186 if (buf[0] != 0x47) {
1187 /* find a new packet start */
1188 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1189 if (mpegts_resync(pb) < 0)
1190 return AVERROR_INVALIDDATA;
1191 else
1192 continue;
1193 } else {
1194 skip = raw_packet_size - TS_PACKET_SIZE;
1195 if (skip > 0)
1196 url_fskip(pb, skip);
1197 break;
1198 }
1199 }
1200 return 0;
1201 }
1202
1203 static int handle_packets(MpegTSContext *ts, int nb_packets)
1204 {
1205 AVFormatContext *s = ts->stream;
1206 ByteIOContext *pb = s->pb;
1207 uint8_t packet[TS_PACKET_SIZE];
1208 int packet_num, ret;
1209
1210 ts->stop_parse = 0;
1211 packet_num = 0;
1212 for(;;) {
1213 if (ts->stop_parse>0)
1214 break;
1215 packet_num++;
1216 if (nb_packets != 0 && packet_num >= nb_packets)
1217 break;
1218 ret = read_packet(pb, packet, ts->raw_packet_size);
1219 if (ret != 0)
1220 return ret;
1221 ret = handle_packet(ts, packet);
1222 if (ret != 0)
1223 return ret;
1224 }
1225 return 0;
1226 }
1227
1228 static int mpegts_probe(AVProbeData *p)
1229 {
1230 #if 1
1231 const int size= p->buf_size;
1232 int score, fec_score, dvhs_score;
1233 int check_count= size / TS_FEC_PACKET_SIZE;
1234 #define CHECK_COUNT 10
1235
1236 if (check_count < CHECK_COUNT)
1237 return -1;
1238
1239 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1240 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1241 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1242 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1243
1244 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1245 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1246 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1247 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1248 else return -1;
1249 #else
1250 /* only use the extension for safer guess */
1251 if (match_ext(p->filename, "ts"))
1252 return AVPROBE_SCORE_MAX;
1253 else
1254 return 0;
1255 #endif
1256 }
1257
1258 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1259 (-1) if not available */
1260 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1261 const uint8_t *packet)
1262 {
1263 int afc, len, flags;
1264 const uint8_t *p;
1265 unsigned int v;
1266
1267 afc = (packet[3] >> 4) & 3;
1268 if (afc <= 1)
1269 return -1;
1270 p = packet + 4;
1271 len = p[0];
1272 p++;
1273 if (len == 0)
1274 return -1;
1275 flags = *p++;
1276 len--;
1277 if (!(flags & 0x10))
1278 return -1;
1279 if (len < 6)
1280 return -1;
1281 v = AV_RB32(p);
1282 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1283 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1284 return 0;
1285 }
1286
1287 static int mpegts_read_header(AVFormatContext *s,
1288 AVFormatParameters *ap)
1289 {
1290 MpegTSContext *ts = s->priv_data;
1291 ByteIOContext *pb = s->pb;
1292 uint8_t buf[5*1024];
1293 int len;
1294 int64_t pos;
1295
1296 if (ap) {
1297 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1298 if(ap->mpeg2ts_raw){
1299 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1300 return -1;
1301 }
1302 }
1303
1304 /* read the first 1024 bytes to get packet size */
1305 pos = url_ftell(pb);
1306 len = get_buffer(pb, buf, sizeof(buf));
1307 if (len != sizeof(buf))
1308 goto fail;
1309 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1310 if (ts->raw_packet_size <= 0)
1311 goto fail;
1312 ts->stream = s;
1313 ts->auto_guess = 0;
1314
1315 if (s->iformat == &mpegts_demuxer) {
1316 /* normal demux */
1317
1318 /* first do a scaning to get all the services */
1319 url_fseek(pb, pos, SEEK_SET);
1320
1321 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1322
1323 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1324
1325 handle_packets(ts, s->probesize);
1326 /* if could not find service, enable auto_guess */
1327
1328 ts->auto_guess = 1;
1329
1330 dprintf(ts->stream, "tuning done\n");
1331
1332 s->ctx_flags |= AVFMTCTX_NOHEADER;
1333 } else {
1334 AVStream *st;
1335 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1336 int64_t pcrs[2], pcr_h;
1337 int packet_count[2];
1338 uint8_t packet[TS_PACKET_SIZE];
1339
1340 /* only read packets */
1341
1342 st = av_new_stream(s, 0);
1343 if (!st)
1344 goto fail;
1345 av_set_pts_info(st, 60, 1, 27000000);
1346 st->codec->codec_type = CODEC_TYPE_DATA;
1347 st->codec->codec_id = CODEC_ID_MPEG2TS;
1348
1349 /* we iterate until we find two PCRs to estimate the bitrate */
1350 pcr_pid = -1;
1351 nb_pcrs = 0;
1352 nb_packets = 0;
1353 for(;;) {
1354 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1355 if (ret < 0)
1356 return -1;
1357 pid = AV_RB16(packet + 1) & 0x1fff;
1358 if ((pcr_pid == -1 || pcr_pid == pid) &&
1359 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1360 pcr_pid = pid;
1361 packet_count[nb_pcrs] = nb_packets;
1362 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1363 nb_pcrs++;
1364 if (nb_pcrs >= 2)
1365 break;
1366 }
1367 nb_packets++;
1368 }
1369
1370 /* NOTE1: the bitrate is computed without the FEC */
1371 /* NOTE2: it is only the bitrate of the start of the stream */
1372 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1373 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1374 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1375 st->codec->bit_rate = s->bit_rate;
1376 st->start_time = ts->cur_pcr;
1377 #if 0
1378 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1379 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1380 #endif
1381 }
1382
1383 url_fseek(pb, pos, SEEK_SET);
1384 return 0;
1385 fail:
1386 return -1;
1387 }
1388
1389 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1390
1391 static int mpegts_raw_read_packet(AVFormatContext *s,
1392 AVPacket *pkt)
1393 {
1394 MpegTSContext *ts = s->priv_data;
1395 int ret, i;
1396 int64_t pcr_h, next_pcr_h, pos;
1397 int pcr_l, next_pcr_l;
1398 uint8_t pcr_buf[12];
1399
1400 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1401 return AVERROR(ENOMEM);
1402 pkt->pos= url_ftell(s->pb);
1403 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1404 if (ret < 0) {
1405 av_free_packet(pkt);
1406 return ret;
1407 }
1408 if (ts->mpeg2ts_compute_pcr) {
1409 /* compute exact PCR for each packet */
1410 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1411 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1412 pos = url_ftell(s->pb);
1413 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1414 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1415 get_buffer(s->pb, pcr_buf, 12);
1416 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1417 /* XXX: not precise enough */
1418 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1419 (i + 1);
1420 break;
1421 }
1422 }
1423 url_fseek(s->pb, pos, SEEK_SET);
1424 /* no next PCR found: we use previous increment */
1425 ts->cur_pcr = pcr_h * 300 + pcr_l;
1426 }
1427 pkt->pts = ts->cur_pcr;
1428 pkt->duration = ts->pcr_incr;
1429 ts->cur_pcr += ts->pcr_incr;
1430 }
1431 pkt->stream_index = 0;
1432 return 0;
1433 }
1434
1435 static int mpegts_read_packet(AVFormatContext *s,
1436 AVPacket *pkt)
1437 {
1438 MpegTSContext *ts = s->priv_data;
1439 int ret, i;
1440
1441 if (url_ftell(s->pb) != ts->last_pos) {
1442 /* seek detected, flush pes buffer */
1443 for (i = 0; i < NB_PID_MAX; i++) {
1444 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1445 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1446 av_freep(&pes->buffer);
1447 pes->data_index = 0;
1448 pes->state = MPEGTS_SKIP; /* skip until pes header */
1449 }
1450 }
1451 }
1452
1453 ts->pkt = pkt;
1454 ret = handle_packets(ts, 0);
1455 if (ret < 0) {
1456 /* flush pes data left */
1457 for (i = 0; i < NB_PID_MAX; i++) {
1458 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1459 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1460 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1461 new_pes_packet(pes, pkt);
1462 ret = 0;
1463 break;
1464 }
1465 }
1466 }
1467 }
1468
1469 ts->last_pos = url_ftell(s->pb);
1470
1471 return ret;
1472 }
1473
1474 static int mpegts_read_close(AVFormatContext *s)
1475 {
1476 MpegTSContext *ts = s->priv_data;
1477 int i;
1478
1479 clear_programs(ts);
1480
1481 for(i=0;i<NB_PID_MAX;i++)
1482 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1483
1484 return 0;
1485 }
1486
1487 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1488 int64_t *ppos, int64_t pos_limit)
1489 {
1490 MpegTSContext *ts = s->priv_data;
1491 int64_t pos, timestamp;
1492 uint8_t buf[TS_PACKET_SIZE];
1493 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1494 const int find_next= 1;
1495 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1496 if (find_next) {
1497 for(;;) {
1498 url_fseek(s->pb, pos, SEEK_SET);
1499 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1500 return AV_NOPTS_VALUE;
1501 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1502 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1503 break;
1504 }
1505 pos += ts->raw_packet_size;
1506 }
1507 } else {
1508 for(;;) {
1509 pos -= ts->raw_packet_size;
1510 if (pos < 0)
1511 return AV_NOPTS_VALUE;
1512 url_fseek(s->pb, pos, SEEK_SET);
1513 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1514 return AV_NOPTS_VALUE;
1515 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1516 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1517 break;
1518 }
1519 }
1520 }
1521 *ppos = pos;
1522
1523 return timestamp;
1524 }
1525
1526 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags);
1527
1528 static int read_seek2(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t target_ts, int64_t max_ts, int flags)
1529 {
1530 int64_t pos;
1531
1532 int64_t ts_ret, ts_adj;
1533 int stream_index_gen_search;
1534 AVStream *st;
1535 AVParserState *backup;
1536
1537 backup = ff_store_parser_state(s);
1538
1539 // detect direction of seeking for search purposes
1540 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ? AVSEEK_FLAG_BACKWARD : 0;
1541
1542 if (flags & AVSEEK_FLAG_BYTE) {
1543 /* use position directly, we will search starting from it */
1544 pos = target_ts;
1545 } else {
1546 /* search for some position with good timestamp match */
1547 if(stream_index < 0){
1548 stream_index_gen_search = av_find_default_stream_index(s);
1549 if (stream_index_gen_search < 0) {
1550 ff_restore_parser_state(s, backup);
1551 return -1;
1552 }
1553
1554 st = s->streams[stream_index_gen_search];
1555 /* timestamp for default must be expressed in AV_TIME_BASE units */
1556 ts_adj = av_rescale(target_ts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1557 } else {
1558 ts_adj = target_ts;
1559 stream_index_gen_search = stream_index;
1560 }
1561 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1562 0, INT64_MAX, -1,
1563 AV_NOPTS_VALUE,
1564 AV_NOPTS_VALUE,
1565 flags, &ts_ret, mpegts_get_pcr);
1566 if (pos < 0) {
1567 ff_restore_parser_state(s, backup);
1568 return -1;
1569 }
1570 }
1571
1572 /* search for actual matching keyframe/starting position for all streams */
1573 if (ff_gen_syncpoint_search(s, stream_index, pos, min_ts, target_ts, max_ts, flags) < 0) {
1574 ff_restore_parser_state(s, backup);
1575 return -1;
1576 }
1577
1578 ff_free_parser_state(s, backup);
1579 return 0;
1580 }
1581
1582 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1583 {
1584 int ret;
1585 if (flags & AVSEEK_FLAG_BACKWARD) {
1586 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1587 if (ret < 0) {
1588 // for compatibility reasons, seek to best-fitting timestamp
1589 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags & ~AVSEEK_FLAG_BACKWARD);
1590 }
1591 } else {
1592 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1593 if (ret < 0) {
1594 // for compatibility reasons, seek to best-fitting timestamp
1595 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1596 }
1597 }
1598 return ret;
1599 }
1600
1601 /**************************************************************/
1602 /* parsing functions - called from other demuxers such as RTP */
1603
1604 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1605 {
1606 MpegTSContext *ts;
1607
1608 ts = av_mallocz(sizeof(MpegTSContext));
1609 if (!ts)
1610 return NULL;
1611 /* no stream case, currently used by RTP */
1612 ts->raw_packet_size = TS_PACKET_SIZE;
1613 ts->stream = s;
1614 ts->auto_guess = 1;
1615 return ts;
1616 }
1617
1618 /* return the consumed length if a packet was output, or -1 if no
1619 packet is output */
1620 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1621 const uint8_t *buf, int len)
1622 {
1623 int len1;
1624
1625 len1 = len;
1626 ts->pkt = pkt;
1627 ts->stop_parse = 0;
1628 for(;;) {
1629 if (ts->stop_parse>0)
1630 break;
1631 if (len < TS_PACKET_SIZE)
1632 return -1;
1633 if (buf[0] != 0x47) {
1634 buf++;
1635 len--;
1636 } else {
1637 handle_packet(ts, buf);
1638 buf += TS_PACKET_SIZE;
1639 len -= TS_PACKET_SIZE;
1640 }
1641 }
1642 return len1 - len;
1643 }
1644
1645 void mpegts_parse_close(MpegTSContext *ts)
1646 {
1647 int i;
1648
1649 for(i=0;i<NB_PID_MAX;i++)
1650 av_free(ts->pids[i]);
1651 av_free(ts);
1652 }
1653
1654 AVInputFormat mpegts_demuxer = {
1655 "mpegts",
1656 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1657 sizeof(MpegTSContext),
1658 mpegts_probe,
1659 mpegts_read_header,
1660 mpegts_read_packet,
1661 mpegts_read_close,
1662 read_seek,
1663 mpegts_get_pcr,
1664 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1665 .read_seek2 = read_seek2,
1666 };
1667
1668 AVInputFormat mpegtsraw_demuxer = {
1669 "mpegtsraw",
1670 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1671 sizeof(MpegTSContext),
1672 NULL,
1673 mpegts_read_header,
1674 mpegts_raw_read_packet,
1675 mpegts_read_close,
1676 read_seek,
1677 mpegts_get_pcr,
1678 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1679 .read_seek2 = read_seek2,
1680 };