01845ed2f61edd26354854493a18b359c6c27d87
[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 { 0 },
511 };
512
513 /* ATSC ? */
514 static const StreamType MISC_types[] = {
515 { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
516 { 0x8a, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
517 { 0 },
518 };
519
520 static const StreamType REGD_types[] = {
521 { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
522 { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
523 { 0 },
524 };
525
526 /* descriptor present */
527 static const StreamType DESC_types[] = {
528 { 0x6a, CODEC_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
529 { 0x7a, CODEC_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
530 { 0x7b, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
531 { 0x59, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
532 { 0 },
533 };
534
535 static void mpegts_find_stream_type(AVStream *st,
536 uint32_t stream_type, const StreamType *types)
537 {
538 for (; types->stream_type; types++) {
539 if (stream_type == types->stream_type) {
540 st->codec->codec_type = types->codec_type;
541 st->codec->codec_id = types->codec_id;
542 return;
543 }
544 }
545 }
546
547 static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)
548 {
549 AVStream *st = av_new_stream(pes->stream, pes->pid);
550
551 if (!st)
552 return NULL;
553
554 av_set_pts_info(st, 33, 1, 90000);
555 st->priv_data = pes;
556 st->codec->codec_type = CODEC_TYPE_DATA;
557 st->codec->codec_id = CODEC_ID_NONE;
558 st->need_parsing = AVSTREAM_PARSE_FULL;
559 pes->st = st;
560
561 dprintf(pes->stream, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",
562 pes->stream_type, pes->pid, (char*)&prog_reg_desc);
563
564 st->codec->codec_tag = pes->stream_type;
565
566 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
567 if (prog_reg_desc == AV_RL32("HDMV") &&
568 st->codec->codec_id == CODEC_ID_NONE)
569 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
570 if (st->codec->codec_id == CODEC_ID_NONE)
571 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
572
573 /* stream was not present in PMT, guess based on PES start code */
574 if (st->codec->codec_id == CODEC_ID_NONE) {
575 if (code >= 0x1c0 && code <= 0x1df) {
576 st->codec->codec_type = CODEC_TYPE_AUDIO;
577 st->codec->codec_id = CODEC_ID_MP2;
578 } else if (code == 0x1bd) {
579 st->codec->codec_type = CODEC_TYPE_AUDIO;
580 st->codec->codec_id = CODEC_ID_AC3;
581 }
582 }
583
584 return st;
585 }
586
587 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
588 {
589 MpegTSContext *ts = filter->u.section_filter.opaque;
590 SectionHeader h1, *h = &h1;
591 PESContext *pes;
592 AVStream *st;
593 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
594 int program_info_length, pcr_pid, pid, stream_type;
595 int desc_list_len, desc_len, desc_tag;
596 int comp_page, anc_page;
597 char language[4];
598 uint32_t prog_reg_desc = 0; /* registration descriptor */
599
600 #ifdef DEBUG
601 dprintf(ts->stream, "PMT: len %i\n", section_len);
602 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
603 #endif
604
605 p_end = section + section_len - 4;
606 p = section;
607 if (parse_section_header(h, &p, p_end) < 0)
608 return;
609
610 dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
611 h->id, h->sec_num, h->last_sec_num);
612
613 if (h->tid != PMT_TID)
614 return;
615
616 clear_program(ts, h->id);
617 pcr_pid = get16(&p, p_end) & 0x1fff;
618 if (pcr_pid < 0)
619 return;
620 add_pid_to_pmt(ts, h->id, pcr_pid);
621
622 dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
623
624 program_info_length = get16(&p, p_end) & 0xfff;
625 if (program_info_length < 0)
626 return;
627 while(program_info_length >= 2) {
628 uint8_t tag, len;
629 tag = get8(&p, p_end);
630 len = get8(&p, p_end);
631 if(len > program_info_length - 2)
632 //something else is broken, exit the program_descriptors_loop
633 break;
634 program_info_length -= len + 2;
635 if(tag == 0x05 && len >= 4) { // registration descriptor
636 prog_reg_desc = bytestream_get_le32(&p);
637 len -= 4;
638 }
639 p += len;
640 }
641 p += program_info_length;
642 if (p >= p_end)
643 return;
644
645 // stop parsing after pmt, we found header
646 if (!ts->stream->nb_streams)
647 ts->stop_parse = 1;
648
649 for(;;) {
650 st = 0;
651 stream_type = get8(&p, p_end);
652 if (stream_type < 0)
653 break;
654 pid = get16(&p, p_end) & 0x1fff;
655 if (pid < 0)
656 break;
657
658 /* now create ffmpeg stream */
659 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
660 pes = ts->pids[pid]->u.pes_filter.opaque;
661 st = pes->st;
662 } else {
663 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
664 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
665 if (pes)
666 st = new_pes_av_stream(pes, prog_reg_desc, 0);
667 }
668
669 if (!st)
670 return;
671
672 add_pid_to_pmt(ts, h->id, pid);
673
674 av_program_add_stream_index(ts->stream, h->id, st->index);
675
676 desc_list_len = get16(&p, p_end) & 0xfff;
677 if (desc_list_len < 0)
678 break;
679 desc_list_end = p + desc_list_len;
680 if (desc_list_end > p_end)
681 break;
682 for(;;) {
683 desc_tag = get8(&p, desc_list_end);
684 if (desc_tag < 0)
685 break;
686 desc_len = get8(&p, desc_list_end);
687 if (desc_len < 0)
688 break;
689 desc_end = p + desc_len;
690 if (desc_end > desc_list_end)
691 break;
692
693 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
694 desc_tag, desc_len);
695
696 if (st->codec->codec_id == CODEC_ID_NONE &&
697 stream_type == STREAM_TYPE_PRIVATE_DATA)
698 mpegts_find_stream_type(st, desc_tag, DESC_types);
699
700 switch(desc_tag) {
701 case 0x59: /* subtitling descriptor */
702 language[0] = get8(&p, desc_end);
703 language[1] = get8(&p, desc_end);
704 language[2] = get8(&p, desc_end);
705 language[3] = 0;
706 get8(&p, desc_end);
707 comp_page = get16(&p, desc_end);
708 anc_page = get16(&p, desc_end);
709 st->codec->sub_id = (anc_page << 16) | comp_page;
710 av_metadata_set(&st->metadata, "language", language);
711 break;
712 case 0x0a: /* ISO 639 language descriptor */
713 language[0] = get8(&p, desc_end);
714 language[1] = get8(&p, desc_end);
715 language[2] = get8(&p, desc_end);
716 language[3] = 0;
717 av_metadata_set(&st->metadata, "language", language);
718 break;
719 case 0x05: /* registration descriptor */
720 st->codec->codec_tag = bytestream_get_le32(&p);
721 dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
722 if (st->codec->codec_id == CODEC_ID_NONE &&
723 stream_type == STREAM_TYPE_PRIVATE_DATA)
724 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
725 break;
726 default:
727 break;
728 }
729 p = desc_end;
730 }
731 p = desc_list_end;
732 }
733 /* all parameters are there */
734 mpegts_close_filter(ts, filter);
735 }
736
737 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
738 {
739 MpegTSContext *ts = filter->u.section_filter.opaque;
740 SectionHeader h1, *h = &h1;
741 const uint8_t *p, *p_end;
742 int sid, pmt_pid;
743
744 #ifdef DEBUG
745 dprintf(ts->stream, "PAT:\n");
746 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
747 #endif
748 p_end = section + section_len - 4;
749 p = section;
750 if (parse_section_header(h, &p, p_end) < 0)
751 return;
752 if (h->tid != PAT_TID)
753 return;
754
755 clear_programs(ts);
756 for(;;) {
757 sid = get16(&p, p_end);
758 if (sid < 0)
759 break;
760 pmt_pid = get16(&p, p_end) & 0x1fff;
761 if (pmt_pid < 0)
762 break;
763
764 dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
765
766 if (sid == 0x0000) {
767 /* NIT info */
768 } else {
769 av_new_program(ts->stream, sid);
770 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
771 add_pat_entry(ts, sid);
772 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
773 add_pid_to_pmt(ts, sid, pmt_pid);
774 }
775 }
776 }
777
778 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
779 {
780 MpegTSContext *ts = filter->u.section_filter.opaque;
781 SectionHeader h1, *h = &h1;
782 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
783 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
784 char *name, *provider_name;
785
786 #ifdef DEBUG
787 dprintf(ts->stream, "SDT:\n");
788 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
789 #endif
790
791 p_end = section + section_len - 4;
792 p = section;
793 if (parse_section_header(h, &p, p_end) < 0)
794 return;
795 if (h->tid != SDT_TID)
796 return;
797 onid = get16(&p, p_end);
798 if (onid < 0)
799 return;
800 val = get8(&p, p_end);
801 if (val < 0)
802 return;
803 for(;;) {
804 sid = get16(&p, p_end);
805 if (sid < 0)
806 break;
807 val = get8(&p, p_end);
808 if (val < 0)
809 break;
810 desc_list_len = get16(&p, p_end) & 0xfff;
811 if (desc_list_len < 0)
812 break;
813 desc_list_end = p + desc_list_len;
814 if (desc_list_end > p_end)
815 break;
816 for(;;) {
817 desc_tag = get8(&p, desc_list_end);
818 if (desc_tag < 0)
819 break;
820 desc_len = get8(&p, desc_list_end);
821 desc_end = p + desc_len;
822 if (desc_end > desc_list_end)
823 break;
824
825 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
826 desc_tag, desc_len);
827
828 switch(desc_tag) {
829 case 0x48:
830 service_type = get8(&p, p_end);
831 if (service_type < 0)
832 break;
833 provider_name = getstr8(&p, p_end);
834 if (!provider_name)
835 break;
836 name = getstr8(&p, p_end);
837 if (name) {
838 AVProgram *program = av_new_program(ts->stream, sid);
839 if(program) {
840 av_metadata_set(&program->metadata, "name", name);
841 av_metadata_set(&program->metadata, "provider_name", provider_name);
842 }
843 }
844 av_free(name);
845 av_free(provider_name);
846 break;
847 default:
848 break;
849 }
850 p = desc_end;
851 }
852 p = desc_list_end;
853 }
854 }
855
856 static int64_t get_pts(const uint8_t *p)
857 {
858 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
859 pts |= (AV_RB16(p + 1) >> 1) << 15;
860 pts |= AV_RB16(p + 3) >> 1;
861 return pts;
862 }
863
864 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
865 {
866 av_init_packet(pkt);
867
868 pkt->destruct = av_destruct_packet;
869 pkt->data = pes->buffer;
870 pkt->size = pes->data_index;
871 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
872
873 pkt->stream_index = pes->st->index;
874 pkt->pts = pes->pts;
875 pkt->dts = pes->dts;
876 /* store position of first TS packet of this PES packet */
877 pkt->pos = pes->ts_packet_pos;
878
879 /* reset pts values */
880 pes->pts = AV_NOPTS_VALUE;
881 pes->dts = AV_NOPTS_VALUE;
882 pes->buffer = NULL;
883 pes->data_index = 0;
884 }
885
886 /* return non zero if a packet could be constructed */
887 static int mpegts_push_data(MpegTSFilter *filter,
888 const uint8_t *buf, int buf_size, int is_start,
889 int64_t pos)
890 {
891 PESContext *pes = filter->u.pes_filter.opaque;
892 MpegTSContext *ts = pes->ts;
893 const uint8_t *p;
894 int len, code;
895
896 if(!ts->pkt)
897 return 0;
898
899 if (is_start) {
900 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
901 new_pes_packet(pes, ts->pkt);
902 ts->stop_parse = 1;
903 }
904 pes->state = MPEGTS_HEADER;
905 pes->data_index = 0;
906 pes->ts_packet_pos = pos;
907 }
908 p = buf;
909 while (buf_size > 0) {
910 switch(pes->state) {
911 case MPEGTS_HEADER:
912 len = PES_START_SIZE - pes->data_index;
913 if (len > buf_size)
914 len = buf_size;
915 memcpy(pes->header + pes->data_index, p, len);
916 pes->data_index += len;
917 p += len;
918 buf_size -= len;
919 if (pes->data_index == PES_START_SIZE) {
920 /* we got all the PES or section header. We can now
921 decide */
922 #if 0
923 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
924 #endif
925 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
926 pes->header[2] == 0x01) {
927 /* it must be an mpeg2 PES stream */
928 code = pes->header[3] | 0x100;
929 dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
930
931 if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
932 (pes->st && pes->st->discard == AVDISCARD_ALL) ||
933 code == 0x1be) /* padding_stream */
934 goto skip;
935
936 /* stream not present in PMT */
937 if (!pes->st)
938 pes->st = new_pes_av_stream(pes, 0, code);
939 if (!pes->st)
940 return AVERROR(ENOMEM);
941
942 pes->total_size = AV_RB16(pes->header + 4);
943 /* NOTE: a zero total size means the PES size is
944 unbounded */
945 if (!pes->total_size)
946 pes->total_size = MAX_PES_PAYLOAD;
947
948 /* allocate pes buffer */
949 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
950 if (!pes->buffer)
951 return AVERROR(ENOMEM);
952
953 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
954 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
955 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
956 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
957 pes->state = MPEGTS_PESHEADER;
958 if (pes->st->codec->codec_id == CODEC_ID_NONE) {
959 dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
960 pes->pid, pes->stream_type);
961 pes->st->codec->codec_id = CODEC_ID_PROBE;
962 }
963 } else {
964 pes->state = MPEGTS_PAYLOAD;
965 pes->data_index = 0;
966 }
967 } else {
968 /* otherwise, it should be a table */
969 /* skip packet */
970 skip:
971 pes->state = MPEGTS_SKIP;
972 continue;
973 }
974 }
975 break;
976 /**********************************************/
977 /* PES packing parsing */
978 case MPEGTS_PESHEADER:
979 len = PES_HEADER_SIZE - pes->data_index;
980 if (len < 0)
981 return -1;
982 if (len > buf_size)
983 len = buf_size;
984 memcpy(pes->header + pes->data_index, p, len);
985 pes->data_index += len;
986 p += len;
987 buf_size -= len;
988 if (pes->data_index == PES_HEADER_SIZE) {
989 pes->pes_header_size = pes->header[8] + 9;
990 pes->state = MPEGTS_PESHEADER_FILL;
991 }
992 break;
993 case MPEGTS_PESHEADER_FILL:
994 len = pes->pes_header_size - pes->data_index;
995 if (len < 0)
996 return -1;
997 if (len > buf_size)
998 len = buf_size;
999 memcpy(pes->header + pes->data_index, p, len);
1000 pes->data_index += len;
1001 p += len;
1002 buf_size -= len;
1003 if (pes->data_index == pes->pes_header_size) {
1004 const uint8_t *r;
1005 unsigned int flags;
1006
1007 flags = pes->header[7];
1008 r = pes->header + 9;
1009 pes->pts = AV_NOPTS_VALUE;
1010 pes->dts = AV_NOPTS_VALUE;
1011 if ((flags & 0xc0) == 0x80) {
1012 pes->dts = pes->pts = get_pts(r);
1013 r += 5;
1014 } else if ((flags & 0xc0) == 0xc0) {
1015 pes->pts = get_pts(r);
1016 r += 5;
1017 pes->dts = get_pts(r);
1018 r += 5;
1019 }
1020
1021 /* we got the full header. We parse it and get the payload */
1022 pes->state = MPEGTS_PAYLOAD;
1023 pes->data_index = 0;
1024 }
1025 break;
1026 case MPEGTS_PAYLOAD:
1027 if (buf_size > 0) {
1028 if (pes->data_index+buf_size > pes->total_size) {
1029 new_pes_packet(pes, ts->pkt);
1030 pes->total_size = MAX_PES_PAYLOAD;
1031 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
1032 if (!pes->buffer)
1033 return AVERROR(ENOMEM);
1034 ts->stop_parse = 1;
1035 }
1036 memcpy(pes->buffer+pes->data_index, p, buf_size);
1037 pes->data_index += buf_size;
1038 }
1039 buf_size = 0;
1040 break;
1041 case MPEGTS_SKIP:
1042 buf_size = 0;
1043 break;
1044 }
1045 }
1046
1047 return 0;
1048 }
1049
1050 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1051 {
1052 MpegTSFilter *tss;
1053 PESContext *pes;
1054
1055 /* if no pid found, then add a pid context */
1056 pes = av_mallocz(sizeof(PESContext));
1057 if (!pes)
1058 return 0;
1059 pes->ts = ts;
1060 pes->stream = ts->stream;
1061 pes->pid = pid;
1062 pes->pcr_pid = pcr_pid;
1063 pes->stream_type = stream_type;
1064 pes->state = MPEGTS_SKIP;
1065 pes->pts = AV_NOPTS_VALUE;
1066 pes->dts = AV_NOPTS_VALUE;
1067 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1068 if (!tss) {
1069 av_free(pes);
1070 return 0;
1071 }
1072 return pes;
1073 }
1074
1075 /* handle one TS packet */
1076 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1077 {
1078 AVFormatContext *s = ts->stream;
1079 MpegTSFilter *tss;
1080 int len, pid, cc, cc_ok, afc, is_start;
1081 const uint8_t *p, *p_end;
1082 int64_t pos;
1083
1084 pid = AV_RB16(packet + 1) & 0x1fff;
1085 if(pid && discard_pid(ts, pid))
1086 return 0;
1087 is_start = packet[1] & 0x40;
1088 tss = ts->pids[pid];
1089 if (ts->auto_guess && tss == NULL && is_start) {
1090 add_pes_stream(ts, pid, -1, 0);
1091 tss = ts->pids[pid];
1092 }
1093 if (!tss)
1094 return 0;
1095
1096 /* continuity check (currently not used) */
1097 cc = (packet[3] & 0xf);
1098 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1099 tss->last_cc = cc;
1100
1101 /* skip adaptation field */
1102 afc = (packet[3] >> 4) & 3;
1103 p = packet + 4;
1104 if (afc == 0) /* reserved value */
1105 return 0;
1106 if (afc == 2) /* adaptation field only */
1107 return 0;
1108 if (afc == 3) {
1109 /* skip adapation field */
1110 p += p[0] + 1;
1111 }
1112 /* if past the end of packet, ignore */
1113 p_end = packet + TS_PACKET_SIZE;
1114 if (p >= p_end)
1115 return 0;
1116
1117 pos = url_ftell(ts->stream->pb);
1118 ts->pos47= pos % ts->raw_packet_size;
1119
1120 if (tss->type == MPEGTS_SECTION) {
1121 if (is_start) {
1122 /* pointer field present */
1123 len = *p++;
1124 if (p + len > p_end)
1125 return 0;
1126 if (len && cc_ok) {
1127 /* write remaining section bytes */
1128 write_section_data(s, tss,
1129 p, len, 0);
1130 /* check whether filter has been closed */
1131 if (!ts->pids[pid])
1132 return 0;
1133 }
1134 p += len;
1135 if (p < p_end) {
1136 write_section_data(s, tss,
1137 p, p_end - p, 1);
1138 }
1139 } else {
1140 if (cc_ok) {
1141 write_section_data(s, tss,
1142 p, p_end - p, 0);
1143 }
1144 }
1145 } else {
1146 int ret;
1147 // Note: The position here points actually behind the current packet.
1148 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1149 pos - ts->raw_packet_size)) < 0)
1150 return ret;
1151 }
1152
1153 return 0;
1154 }
1155
1156 /* XXX: try to find a better synchro over several packets (use
1157 get_packet_size() ?) */
1158 static int mpegts_resync(ByteIOContext *pb)
1159 {
1160 int c, i;
1161
1162 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1163 c = url_fgetc(pb);
1164 if (c < 0)
1165 return -1;
1166 if (c == 0x47) {
1167 url_fseek(pb, -1, SEEK_CUR);
1168 return 0;
1169 }
1170 }
1171 /* no sync found */
1172 return -1;
1173 }
1174
1175 /* return -1 if error or EOF. Return 0 if OK. */
1176 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1177 {
1178 int skip, len;
1179
1180 for(;;) {
1181 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1182 if (len != TS_PACKET_SIZE)
1183 return AVERROR(EIO);
1184 /* check paquet sync byte */
1185 if (buf[0] != 0x47) {
1186 /* find a new packet start */
1187 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1188 if (mpegts_resync(pb) < 0)
1189 return AVERROR_INVALIDDATA;
1190 else
1191 continue;
1192 } else {
1193 skip = raw_packet_size - TS_PACKET_SIZE;
1194 if (skip > 0)
1195 url_fskip(pb, skip);
1196 break;
1197 }
1198 }
1199 return 0;
1200 }
1201
1202 static int handle_packets(MpegTSContext *ts, int nb_packets)
1203 {
1204 AVFormatContext *s = ts->stream;
1205 ByteIOContext *pb = s->pb;
1206 uint8_t packet[TS_PACKET_SIZE];
1207 int packet_num, ret;
1208
1209 ts->stop_parse = 0;
1210 packet_num = 0;
1211 for(;;) {
1212 if (ts->stop_parse>0)
1213 break;
1214 packet_num++;
1215 if (nb_packets != 0 && packet_num >= nb_packets)
1216 break;
1217 ret = read_packet(pb, packet, ts->raw_packet_size);
1218 if (ret != 0)
1219 return ret;
1220 ret = handle_packet(ts, packet);
1221 if (ret != 0)
1222 return ret;
1223 }
1224 return 0;
1225 }
1226
1227 static int mpegts_probe(AVProbeData *p)
1228 {
1229 #if 1
1230 const int size= p->buf_size;
1231 int score, fec_score, dvhs_score;
1232 int check_count= size / TS_FEC_PACKET_SIZE;
1233 #define CHECK_COUNT 10
1234
1235 if (check_count < CHECK_COUNT)
1236 return -1;
1237
1238 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1239 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1240 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1241 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1242
1243 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1244 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1245 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1246 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1247 else return -1;
1248 #else
1249 /* only use the extension for safer guess */
1250 if (match_ext(p->filename, "ts"))
1251 return AVPROBE_SCORE_MAX;
1252 else
1253 return 0;
1254 #endif
1255 }
1256
1257 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1258 (-1) if not available */
1259 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1260 const uint8_t *packet)
1261 {
1262 int afc, len, flags;
1263 const uint8_t *p;
1264 unsigned int v;
1265
1266 afc = (packet[3] >> 4) & 3;
1267 if (afc <= 1)
1268 return -1;
1269 p = packet + 4;
1270 len = p[0];
1271 p++;
1272 if (len == 0)
1273 return -1;
1274 flags = *p++;
1275 len--;
1276 if (!(flags & 0x10))
1277 return -1;
1278 if (len < 6)
1279 return -1;
1280 v = AV_RB32(p);
1281 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1282 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1283 return 0;
1284 }
1285
1286 static int mpegts_read_header(AVFormatContext *s,
1287 AVFormatParameters *ap)
1288 {
1289 MpegTSContext *ts = s->priv_data;
1290 ByteIOContext *pb = s->pb;
1291 uint8_t buf[5*1024];
1292 int len;
1293 int64_t pos;
1294
1295 if (ap) {
1296 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1297 if(ap->mpeg2ts_raw){
1298 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1299 return -1;
1300 }
1301 }
1302
1303 /* read the first 1024 bytes to get packet size */
1304 pos = url_ftell(pb);
1305 len = get_buffer(pb, buf, sizeof(buf));
1306 if (len != sizeof(buf))
1307 goto fail;
1308 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1309 if (ts->raw_packet_size <= 0)
1310 goto fail;
1311 ts->stream = s;
1312 ts->auto_guess = 0;
1313
1314 if (s->iformat == &mpegts_demuxer) {
1315 /* normal demux */
1316
1317 /* first do a scaning to get all the services */
1318 url_fseek(pb, pos, SEEK_SET);
1319
1320 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1321
1322 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1323
1324 handle_packets(ts, s->probesize);
1325 /* if could not find service, enable auto_guess */
1326
1327 ts->auto_guess = 1;
1328
1329 dprintf(ts->stream, "tuning done\n");
1330
1331 s->ctx_flags |= AVFMTCTX_NOHEADER;
1332 } else {
1333 AVStream *st;
1334 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1335 int64_t pcrs[2], pcr_h;
1336 int packet_count[2];
1337 uint8_t packet[TS_PACKET_SIZE];
1338
1339 /* only read packets */
1340
1341 st = av_new_stream(s, 0);
1342 if (!st)
1343 goto fail;
1344 av_set_pts_info(st, 60, 1, 27000000);
1345 st->codec->codec_type = CODEC_TYPE_DATA;
1346 st->codec->codec_id = CODEC_ID_MPEG2TS;
1347
1348 /* we iterate until we find two PCRs to estimate the bitrate */
1349 pcr_pid = -1;
1350 nb_pcrs = 0;
1351 nb_packets = 0;
1352 for(;;) {
1353 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1354 if (ret < 0)
1355 return -1;
1356 pid = AV_RB16(packet + 1) & 0x1fff;
1357 if ((pcr_pid == -1 || pcr_pid == pid) &&
1358 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1359 pcr_pid = pid;
1360 packet_count[nb_pcrs] = nb_packets;
1361 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1362 nb_pcrs++;
1363 if (nb_pcrs >= 2)
1364 break;
1365 }
1366 nb_packets++;
1367 }
1368
1369 /* NOTE1: the bitrate is computed without the FEC */
1370 /* NOTE2: it is only the bitrate of the start of the stream */
1371 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1372 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1373 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1374 st->codec->bit_rate = s->bit_rate;
1375 st->start_time = ts->cur_pcr;
1376 #if 0
1377 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1378 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1379 #endif
1380 }
1381
1382 url_fseek(pb, pos, SEEK_SET);
1383 return 0;
1384 fail:
1385 return -1;
1386 }
1387
1388 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1389
1390 static int mpegts_raw_read_packet(AVFormatContext *s,
1391 AVPacket *pkt)
1392 {
1393 MpegTSContext *ts = s->priv_data;
1394 int ret, i;
1395 int64_t pcr_h, next_pcr_h, pos;
1396 int pcr_l, next_pcr_l;
1397 uint8_t pcr_buf[12];
1398
1399 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1400 return AVERROR(ENOMEM);
1401 pkt->pos= url_ftell(s->pb);
1402 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1403 if (ret < 0) {
1404 av_free_packet(pkt);
1405 return ret;
1406 }
1407 if (ts->mpeg2ts_compute_pcr) {
1408 /* compute exact PCR for each packet */
1409 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1410 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1411 pos = url_ftell(s->pb);
1412 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1413 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1414 get_buffer(s->pb, pcr_buf, 12);
1415 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1416 /* XXX: not precise enough */
1417 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1418 (i + 1);
1419 break;
1420 }
1421 }
1422 url_fseek(s->pb, pos, SEEK_SET);
1423 /* no next PCR found: we use previous increment */
1424 ts->cur_pcr = pcr_h * 300 + pcr_l;
1425 }
1426 pkt->pts = ts->cur_pcr;
1427 pkt->duration = ts->pcr_incr;
1428 ts->cur_pcr += ts->pcr_incr;
1429 }
1430 pkt->stream_index = 0;
1431 return 0;
1432 }
1433
1434 static int mpegts_read_packet(AVFormatContext *s,
1435 AVPacket *pkt)
1436 {
1437 MpegTSContext *ts = s->priv_data;
1438 int ret, i;
1439
1440 if (url_ftell(s->pb) != ts->last_pos) {
1441 /* seek detected, flush pes buffer */
1442 for (i = 0; i < NB_PID_MAX; i++) {
1443 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1444 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1445 av_freep(&pes->buffer);
1446 pes->data_index = 0;
1447 pes->state = MPEGTS_SKIP; /* skip until pes header */
1448 }
1449 }
1450 }
1451
1452 ts->pkt = pkt;
1453 ret = handle_packets(ts, 0);
1454 if (ret < 0) {
1455 /* flush pes data left */
1456 for (i = 0; i < NB_PID_MAX; i++) {
1457 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1458 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1459 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1460 new_pes_packet(pes, pkt);
1461 ret = 0;
1462 break;
1463 }
1464 }
1465 }
1466 }
1467
1468 ts->last_pos = url_ftell(s->pb);
1469
1470 return ret;
1471 }
1472
1473 static int mpegts_read_close(AVFormatContext *s)
1474 {
1475 MpegTSContext *ts = s->priv_data;
1476 int i;
1477
1478 clear_programs(ts);
1479
1480 for(i=0;i<NB_PID_MAX;i++)
1481 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1482
1483 return 0;
1484 }
1485
1486 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1487 int64_t *ppos, int64_t pos_limit)
1488 {
1489 MpegTSContext *ts = s->priv_data;
1490 int64_t pos, timestamp;
1491 uint8_t buf[TS_PACKET_SIZE];
1492 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1493 const int find_next= 1;
1494 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1495 if (find_next) {
1496 for(;;) {
1497 url_fseek(s->pb, pos, SEEK_SET);
1498 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1499 return AV_NOPTS_VALUE;
1500 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1501 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1502 break;
1503 }
1504 pos += ts->raw_packet_size;
1505 }
1506 } else {
1507 for(;;) {
1508 pos -= ts->raw_packet_size;
1509 if (pos < 0)
1510 return AV_NOPTS_VALUE;
1511 url_fseek(s->pb, pos, SEEK_SET);
1512 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1513 return AV_NOPTS_VALUE;
1514 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1515 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1516 break;
1517 }
1518 }
1519 }
1520 *ppos = pos;
1521
1522 return timestamp;
1523 }
1524
1525 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags);
1526
1527 static int read_seek2(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t target_ts, int64_t max_ts, int flags)
1528 {
1529 int64_t pos;
1530
1531 int64_t ts_ret, ts_adj;
1532 int stream_index_gen_search;
1533 AVStream *st;
1534 AVParserState *backup;
1535
1536 backup = ff_store_parser_state(s);
1537
1538 // detect direction of seeking for search purposes
1539 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ? AVSEEK_FLAG_BACKWARD : 0;
1540
1541 if (flags & AVSEEK_FLAG_BYTE) {
1542 /* use position directly, we will search starting from it */
1543 pos = target_ts;
1544 } else {
1545 /* search for some position with good timestamp match */
1546 if(stream_index < 0){
1547 stream_index_gen_search = av_find_default_stream_index(s);
1548 if (stream_index_gen_search < 0) {
1549 ff_restore_parser_state(s, backup);
1550 return -1;
1551 }
1552
1553 st = s->streams[stream_index_gen_search];
1554 /* timestamp for default must be expressed in AV_TIME_BASE units */
1555 ts_adj = av_rescale(target_ts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1556 } else {
1557 ts_adj = target_ts;
1558 stream_index_gen_search = stream_index;
1559 }
1560 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1561 0, INT64_MAX, -1,
1562 AV_NOPTS_VALUE,
1563 AV_NOPTS_VALUE,
1564 flags, &ts_ret, mpegts_get_pcr);
1565 if (pos < 0) {
1566 ff_restore_parser_state(s, backup);
1567 return -1;
1568 }
1569 }
1570
1571 /* search for actual matching keyframe/starting position for all streams */
1572 if (ff_gen_syncpoint_search(s, stream_index, pos, min_ts, target_ts, max_ts, flags) < 0) {
1573 ff_restore_parser_state(s, backup);
1574 return -1;
1575 }
1576
1577 ff_free_parser_state(s, backup);
1578 return 0;
1579 }
1580
1581 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1582 {
1583 int ret;
1584 if (flags & AVSEEK_FLAG_BACKWARD) {
1585 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1586 if (ret < 0) {
1587 // for compatibility reasons, seek to best-fitting timestamp
1588 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags & ~AVSEEK_FLAG_BACKWARD);
1589 }
1590 } else {
1591 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1592 if (ret < 0) {
1593 // for compatibility reasons, seek to best-fitting timestamp
1594 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1595 }
1596 }
1597 return ret;
1598 }
1599
1600 /**************************************************************/
1601 /* parsing functions - called from other demuxers such as RTP */
1602
1603 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1604 {
1605 MpegTSContext *ts;
1606
1607 ts = av_mallocz(sizeof(MpegTSContext));
1608 if (!ts)
1609 return NULL;
1610 /* no stream case, currently used by RTP */
1611 ts->raw_packet_size = TS_PACKET_SIZE;
1612 ts->stream = s;
1613 ts->auto_guess = 1;
1614 return ts;
1615 }
1616
1617 /* return the consumed length if a packet was output, or -1 if no
1618 packet is output */
1619 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1620 const uint8_t *buf, int len)
1621 {
1622 int len1;
1623
1624 len1 = len;
1625 ts->pkt = pkt;
1626 ts->stop_parse = 0;
1627 for(;;) {
1628 if (ts->stop_parse>0)
1629 break;
1630 if (len < TS_PACKET_SIZE)
1631 return -1;
1632 if (buf[0] != 0x47) {
1633 buf++;
1634 len--;
1635 } else {
1636 handle_packet(ts, buf);
1637 buf += TS_PACKET_SIZE;
1638 len -= TS_PACKET_SIZE;
1639 }
1640 }
1641 return len1 - len;
1642 }
1643
1644 void mpegts_parse_close(MpegTSContext *ts)
1645 {
1646 int i;
1647
1648 for(i=0;i<NB_PID_MAX;i++)
1649 av_free(ts->pids[i]);
1650 av_free(ts);
1651 }
1652
1653 AVInputFormat mpegts_demuxer = {
1654 "mpegts",
1655 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1656 sizeof(MpegTSContext),
1657 mpegts_probe,
1658 mpegts_read_header,
1659 mpegts_read_packet,
1660 mpegts_read_close,
1661 read_seek,
1662 mpegts_get_pcr,
1663 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1664 .read_seek2 = read_seek2,
1665 };
1666
1667 AVInputFormat mpegtsraw_demuxer = {
1668 "mpegtsraw",
1669 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1670 sizeof(MpegTSContext),
1671 NULL,
1672 mpegts_read_header,
1673 mpegts_raw_read_packet,
1674 mpegts_read_close,
1675 read_seek,
1676 mpegts_get_pcr,
1677 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1678 .read_seek2 = read_seek2,
1679 };