summaryrefslogtreecommitdiff
path: root/libavformat/mpegts.c (plain)
blob: a9c5ca0bdbe375ab645dbbadda54c4d45ccf7436
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#include "libavutil/buffer.h"
23#include "libavutil/crc.h"
24#include "libavutil/intreadwrite.h"
25#include "libavutil/log.h"
26#include "libavutil/dict.h"
27#include "libavutil/mathematics.h"
28#include "libavutil/opt.h"
29#include "libavutil/avassert.h"
30#include "libavcodec/bytestream.h"
31#include "libavcodec/get_bits.h"
32#include "libavcodec/mathops.h"
33#include "avformat.h"
34#include "mpegts.h"
35#include "internal.h"
36#include "avio_internal.h"
37#include "seek.h"
38#include "mpeg.h"
39#include "isom.h"
40
41/* maximum size in which we look for synchronisation if
42 synchronisation is lost */
43#define MAX_RESYNC_SIZE 65536
44
45#define MAX_PES_PAYLOAD 200*1024
46
47#define MAX_MP4_DESCR_COUNT 16
48
49enum MpegTSFilterType {
50 MPEGTS_PES,
51 MPEGTS_SECTION,
52};
53
54typedef struct MpegTSFilter MpegTSFilter;
55
56typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos, int64_t cur_pcr);
57
58typedef struct MpegTSPESFilter {
59 PESCallback *pes_cb;
60 void *opaque;
61} MpegTSPESFilter;
62
63typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
64
65typedef void SetServiceCallback(void *opaque, int ret);
66
67typedef struct MpegTSSectionFilter {
68 int section_index;
69 int section_h_size;
70 uint8_t *section_buf;
71 unsigned int check_crc:1;
72 unsigned int end_of_section_reached:1;
73 SectionCallback *section_cb;
74 void *opaque;
75} MpegTSSectionFilter;
76
77struct MpegTSFilter {
78 int pid;
79 int es_id;
80 int last_cc; /* last cc code (-1 if first packet) */
81 enum MpegTSFilterType type;
82 union {
83 MpegTSPESFilter pes_filter;
84 MpegTSSectionFilter section_filter;
85 } u;
86};
87
88#define MAX_PIDS_PER_PROGRAM 64
89struct Program {
90 unsigned int id; //program id/service id
91 unsigned int nb_pids;
92 unsigned int pids[MAX_PIDS_PER_PROGRAM];
93};
94
95struct MpegTSContext {
96 const AVClass *class;
97 /* user data */
98 AVFormatContext *stream;
99 /** raw packet size, including FEC if present */
100 int raw_packet_size;
101
102 int size_stat[3];
103 int size_stat_count;
104#define SIZE_STAT_THRESHOLD 10
105
106 int64_t pos47_full;
107
108 /** if true, all pids are analyzed to find streams */
109 int auto_guess;
110
111 /** compute exact PCR for each transport stream packet */
112 int mpeg2ts_compute_pcr;
113
114 /** fix dvb teletext pts */
115 int fix_teletext_pts;
116
117 int64_t cur_pcr; /**< used to estimate the exact PCR */
118 int pcr_incr; /**< used to estimate the exact PCR */
119
120 /* data needed to handle file based ts */
121 /** stop parsing loop */
122 int stop_parse;
123 /** packet containing Audio/Video data */
124 AVPacket *pkt;
125 /** to detect seek */
126 int64_t last_pos;
127
128 int64_t first_pcrscr;
129
130 /******************************************/
131 /* private mpegts data */
132 /* scan context */
133 /** structure to keep track of Program->pids mapping */
134 unsigned int nb_prg;
135 struct Program *prg;
136
137 int8_t crc_validity[NB_PID_MAX];
138
139 /** filters for various streams specified by PMT + for the PAT and PMT */
140 MpegTSFilter *pids[NB_PID_MAX];
141 int current_pid;
142};
143
144static const AVOption mpegtsraw_options[] = {
145 {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
146 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
147 { NULL },
148};
149
150static const AVClass mpegtsraw_class = {
151 .class_name = "mpegtsraw demuxer",
152 .item_name = av_default_item_name,
153 .option = mpegtsraw_options,
154 .version = LIBAVUTIL_VERSION_INT,
155};
156
157static const AVOption mpegts_options[] = {
158 {"fix_teletext_pts", "Try to fix pts values of dvb teletext streams.", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_INT,
159 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
160 { NULL },
161};
162
163static const AVClass mpegts_class = {
164 .class_name = "mpegts demuxer",
165 .item_name = av_default_item_name,
166 .option = mpegts_options,
167 .version = LIBAVUTIL_VERSION_INT,
168};
169
170/* TS stream handling */
171
172enum MpegTSState {
173 MPEGTS_HEADER = 0,
174 MPEGTS_PESHEADER,
175 MPEGTS_PESHEADER_FILL,
176 MPEGTS_PAYLOAD,
177 MPEGTS_SKIP,
178};
179
180/* enough for PES header + length */
181#define PES_START_SIZE 6
182#define PES_HEADER_SIZE 9
183#define MAX_PES_HEADER_SIZE (9 + 255)
184
185typedef struct PESContext {
186 int pid;
187 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
188 int stream_type;
189 MpegTSContext *ts;
190 AVFormatContext *stream;
191 AVStream *st;
192 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
193 enum MpegTSState state;
194 /* used to get the format */
195 int data_index;
196 int flags; /**< copied to the AVPacket flags */
197 int total_size;
198 int pes_header_size;
199 int extended_stream_id;
200 int64_t pts, dts;
201 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
202 uint8_t header[MAX_PES_HEADER_SIZE];
203 AVBufferRef *buffer;
204 SLConfigDescr sl;
205 int64_t last_pcr;
206} PESContext;
207
208extern AVInputFormat ff_mpegts_demuxer;
209
210static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
211{
212 AVProgram *prg = NULL;
213 int i;
214 for(i=0; i<ts->stream->nb_programs; i++)
215 if(ts->stream->programs[i]->id == programid){
216 prg = ts->stream->programs[i];
217 break;
218 }
219 if (!prg)
220 return;
221 prg->nb_stream_indexes = 0;
222}
223
224static void clear_program(MpegTSContext *ts, unsigned int programid)
225{
226 int i;
227
228 clear_avprogram(ts, programid);
229 for(i=0; i<ts->nb_prg; i++)
230 if(ts->prg[i].id == programid)
231 ts->prg[i].nb_pids = 0;
232}
233
234static void clear_programs(MpegTSContext *ts)
235{
236 av_freep(&ts->prg);
237 ts->nb_prg=0;
238}
239
240static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
241{
242 struct Program *p;
243 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
244 ts->nb_prg = 0;
245 return;
246 }
247 p = &ts->prg[ts->nb_prg];
248 p->id = programid;
249 p->nb_pids = 0;
250 ts->nb_prg++;
251}
252
253static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
254{
255 int i;
256 struct Program *p = NULL;
257 for(i=0; i<ts->nb_prg; i++) {
258 if(ts->prg[i].id == programid) {
259 p = &ts->prg[i];
260 break;
261 }
262 }
263 if(!p)
264 return;
265
266 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
267 return;
268 p->pids[p->nb_pids++] = pid;
269}
270
271static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
272{
273 int i;
274 for(i=0; i<s->nb_programs; i++) {
275 if(s->programs[i]->id == programid) {
276 s->programs[i]->pcr_pid = pid;
277 break;
278 }
279 }
280}
281
282/**
283 * @brief discard_pid() decides if the pid is to be discarded according
284 * to caller's programs selection
285 * @param ts : - TS context
286 * @param pid : - pid
287 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
288 * 0 otherwise
289 */
290static int discard_pid(MpegTSContext *ts, unsigned int pid)
291{
292 int i, j, k;
293 int used = 0, discarded = 0;
294 struct Program *p;
295
296 /* If none of the programs have .discard=AVDISCARD_ALL then there's
297 * no way we have to discard this packet
298 */
299 for (k = 0; k < ts->stream->nb_programs; k++) {
300 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
301 break;
302 }
303 if (k == ts->stream->nb_programs)
304 return 0;
305
306 for(i=0; i<ts->nb_prg; i++) {
307 p = &ts->prg[i];
308 for(j=0; j<p->nb_pids; j++) {
309 if(p->pids[j] != pid)
310 continue;
311 //is program with id p->id set to be discarded?
312 for(k=0; k<ts->stream->nb_programs; k++) {
313 if(ts->stream->programs[k]->id == p->id) {
314 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
315 discarded++;
316 else
317 used++;
318 }
319 }
320 }
321 }
322
323 return !used && discarded;
324}
325
326/**
327 * Assemble PES packets out of TS packets, and then call the "section_cb"
328 * function when they are complete.
329 */
330static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
331 const uint8_t *buf, int buf_size, int is_start)
332{
333 MpegTSContext *ts = s->priv_data;
334 MpegTSSectionFilter *tss = &tss1->u.section_filter;
335 int len;
336
337 if (is_start) {
338 memcpy(tss->section_buf, buf, buf_size);
339 tss->section_index = buf_size;
340 tss->section_h_size = -1;
341 tss->end_of_section_reached = 0;
342 } else {
343 if (tss->end_of_section_reached)
344 return;
345 len = 4096 - tss->section_index;
346 if (buf_size < len)
347 len = buf_size;
348 memcpy(tss->section_buf + tss->section_index, buf, len);
349 tss->section_index += len;
350 }
351
352 /* compute section length if possible */
353 if (tss->section_h_size == -1 && tss->section_index >= 3) {
354 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
355 if (len > 4096)
356 return;
357 tss->section_h_size = len;
358 }
359
360 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
361 int crc_valid = 1;
362 tss->end_of_section_reached = 1;
363
364 if (tss->check_crc){
365 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
366 if (crc_valid){
367 ts->crc_validity[ tss1->pid ] = 100;
368 }else if(ts->crc_validity[ tss1->pid ] > -10){
369 ts->crc_validity[ tss1->pid ]--;
370 }else
371 crc_valid = 2;
372 }
373 if (crc_valid)
374 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
375 }
376}
377
378static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
379 SectionCallback *section_cb, void *opaque,
380 int check_crc)
381
382{
383 MpegTSFilter *filter;
384 MpegTSSectionFilter *sec;
385
386 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
387
388 if (pid >= NB_PID_MAX || ts->pids[pid])
389 return NULL;
390 filter = av_mallocz(sizeof(MpegTSFilter));
391 if (!filter)
392 return NULL;
393 ts->pids[pid] = filter;
394 filter->type = MPEGTS_SECTION;
395 filter->pid = pid;
396 filter->es_id = -1;
397 filter->last_cc = -1;
398 sec = &filter->u.section_filter;
399 sec->section_cb = section_cb;
400 sec->opaque = opaque;
401 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
402 sec->check_crc = check_crc;
403 if (!sec->section_buf) {
404 av_free(filter);
405 return NULL;
406 }
407 return filter;
408}
409
410static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
411 PESCallback *pes_cb,
412 void *opaque)
413{
414 MpegTSFilter *filter;
415 MpegTSPESFilter *pes;
416
417 if (pid >= NB_PID_MAX || ts->pids[pid])
418 return NULL;
419 filter = av_mallocz(sizeof(MpegTSFilter));
420 if (!filter)
421 return NULL;
422 ts->pids[pid] = filter;
423 filter->type = MPEGTS_PES;
424 filter->pid = pid;
425 filter->es_id = -1;
426 filter->last_cc = -1;
427 pes = &filter->u.pes_filter;
428 pes->pes_cb = pes_cb;
429 pes->opaque = opaque;
430 return filter;
431}
432
433static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
434{
435 int pid;
436
437 pid = filter->pid;
438 if (filter->type == MPEGTS_SECTION)
439 av_freep(&filter->u.section_filter.section_buf);
440 else if (filter->type == MPEGTS_PES) {
441 PESContext *pes = filter->u.pes_filter.opaque;
442 av_buffer_unref(&pes->buffer);
443 /* referenced private data will be freed later in
444 * avformat_close_input */
445 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
446 av_freep(&filter->u.pes_filter.opaque);
447 }
448 }
449
450 av_free(filter);
451 ts->pids[pid] = NULL;
452}
453
454static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
455 int stat[TS_MAX_PACKET_SIZE];
456 int i;
457 int x=0;
458 int best_score=0;
459
460 memset(stat, 0, packet_size*sizeof(int));
461
462 for(x=i=0; i<size-3; i++){
463 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
464 stat[x]++;
465 if(stat[x] > best_score){
466 best_score= stat[x];
467 if(index) *index= x;
468 }
469 }
470
471 x++;
472 if(x == packet_size) x= 0;
473 }
474
475 return best_score;
476}
477
478/* autodetect fec presence. Must have at least 1024 bytes */
479static int get_packet_size(const uint8_t *buf, int size)
480{
481 int score, fec_score, dvhs_score;
482
483 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
484 return -1;
485
486 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
487 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
488 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
489 av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
490 score, dvhs_score, fec_score);
491
492 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
493 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
494 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
495 else return -1;
496}
497
498typedef struct SectionHeader {
499 uint8_t tid;
500 uint16_t id;
501 uint8_t version;
502 uint8_t sec_num;
503 uint8_t last_sec_num;
504} SectionHeader;
505
506static inline int get8(const uint8_t **pp, const uint8_t *p_end)
507{
508 const uint8_t *p;
509 int c;
510
511 p = *pp;
512 if (p >= p_end)
513 return -1;
514 c = *p++;
515 *pp = p;
516 return c;
517}
518
519static inline int get16(const uint8_t **pp, const uint8_t *p_end)
520{
521 const uint8_t *p;
522 int c;
523
524 p = *pp;
525 if ((p + 1) >= p_end)
526 return -1;
527 c = AV_RB16(p);
528 p += 2;
529 *pp = p;
530 return c;
531}
532
533/* read and allocate a DVB string preceded by its length */
534static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
535{
536 int len;
537 const uint8_t *p;
538 char *str;
539
540 p = *pp;
541 len = get8(&p, p_end);
542 if (len < 0)
543 return NULL;
544 if ((p + len) > p_end)
545 return NULL;
546 str = av_malloc(len + 1);
547 if (!str)
548 return NULL;
549 memcpy(str, p, len);
550 str[len] = '\0';
551 p += len;
552 *pp = p;
553 return str;
554}
555
556static int parse_section_header(SectionHeader *h,
557 const uint8_t **pp, const uint8_t *p_end)
558{
559 int val;
560
561 val = get8(pp, p_end);
562 if (val < 0)
563 return -1;
564 h->tid = val;
565 *pp += 2;
566 val = get16(pp, p_end);
567 if (val < 0)
568 return -1;
569 h->id = val;
570 val = get8(pp, p_end);
571 if (val < 0)
572 return -1;
573 h->version = (val >> 1) & 0x1f;
574 val = get8(pp, p_end);
575 if (val < 0)
576 return -1;
577 h->sec_num = val;
578 val = get8(pp, p_end);
579 if (val < 0)
580 return -1;
581 h->last_sec_num = val;
582 return 0;
583}
584
585typedef struct {
586 uint32_t stream_type;
587 enum AVMediaType codec_type;
588 enum AVCodecID codec_id;
589} StreamType;
590
591static const StreamType ISO_types[] = {
592 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
593 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
594 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
595 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
596 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
597 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
598 /* Makito encoder sets stream type 0x11 for AAC,
599 * so auto-detect LOAS/LATM instead of hardcoding it. */
600#if !CONFIG_LOAS_DEMUXER
601 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
602#endif
603 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
604 { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
605 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
606 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
607 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
608 { 0 },
609};
610
611static const StreamType HDMV_types[] = {
612 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
613 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
614 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
615 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
616 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
617 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
618 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
619 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
620 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
621 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
622 { 0 },
623};
624
625/* ATSC ? */
626static const StreamType MISC_types[] = {
627 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
628 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
629 { 0 },
630};
631
632static const StreamType REGD_types[] = {
633 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
634 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
635 { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
636 { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
637 { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
638 { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
639 { MKTAG('H','E','V','C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
640 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
641 { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
642 { MKTAG('D','R','A','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DRA },
643 { 0 },
644};
645
646static const StreamType METADATA_types[] = {
647 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
648 { 0 },
649};
650
651/* descriptor present */
652static const StreamType DESC_types[] = {
653 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
654 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
655 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
656 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
657 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
658 { 0 },
659};
660
661static void mpegts_find_stream_type(AVStream *st,
662 uint32_t stream_type, const StreamType *types)
663{
664 if (avcodec_is_open(st->codec)) {
665 av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
666 return;
667 }
668
669 for (; types->stream_type; types++) {
670 if (stream_type == types->stream_type) {
671 st->codec->codec_type = types->codec_type;
672 st->codec->codec_id = types->codec_id;
673 st->request_probe = 0;
674 return;
675 }
676 }
677}
678
679static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
680 uint32_t stream_type, uint32_t prog_reg_desc)
681{
682 int old_codec_type= st->codec->codec_type;
683 int old_codec_id = st->codec->codec_id;
684
685 if (avcodec_is_open(st->codec)) {
686 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
687 return 0;
688 }
689
690 avpriv_set_pts_info(st, 33, 1, 90000);
691 st->priv_data = pes;
692 st->codec->codec_type = AVMEDIA_TYPE_DATA;
693 st->codec->codec_id = AV_CODEC_ID_NONE;
694 st->need_parsing = AVSTREAM_PARSE_FULL;
695 pes->st = st;
696 pes->stream_type = stream_type;
697
698 av_log(pes->stream, AV_LOG_DEBUG,
699 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
700 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
701
702 st->codec->codec_tag = pes->stream_type;
703
704 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
705 if ((prog_reg_desc == AV_RL32("HDMV") ||
706 prog_reg_desc == AV_RL32("HDPR")) &&
707 st->codec->codec_id == AV_CODEC_ID_NONE) {
708 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
709 if (pes->stream_type == 0x83) {
710 // HDMV TrueHD streams also contain an AC3 coded version of the
711 // audio track - add a second stream for this
712 AVStream *sub_st;
713 // priv_data cannot be shared between streams
714 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
715 if (!sub_pes)
716 return AVERROR(ENOMEM);
717 memcpy(sub_pes, pes, sizeof(*sub_pes));
718
719 sub_st = avformat_new_stream(pes->stream, NULL);
720 if (!sub_st) {
721 av_free(sub_pes);
722 return AVERROR(ENOMEM);
723 }
724
725 sub_st->id = pes->pid;
726 avpriv_set_pts_info(sub_st, 33, 1, 90000);
727 sub_st->priv_data = sub_pes;
728 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
729 sub_st->codec->codec_id = AV_CODEC_ID_AC3;
730 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
731 sub_pes->sub_st = pes->sub_st = sub_st;
732 }
733 if (pes->stream_type == 0x81) {
734 // HDMV AC3 streams also contain an TRUEHD coded version of the
735 // audio track - add a second stream for this
736 AVStream *sub_st;
737 // priv_data cannot be shared between streams
738 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
739 if (!sub_pes)
740 return AVERROR(ENOMEM);
741 memcpy(sub_pes, pes, sizeof(*sub_pes));
742
743 sub_st = avformat_new_stream(pes->stream, NULL);
744 if (!sub_st) {
745 av_free(sub_pes);
746 return AVERROR(ENOMEM);
747 }
748
749 sub_st->id = pes->pid;
750 avpriv_set_pts_info(sub_st, 33, 1, 90000);
751 sub_st->priv_data = sub_pes;
752 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
753 sub_st->codec->codec_id = AV_CODEC_ID_TRUEHD;
754 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
755 sub_st->discard = AVDISCARD_ALL;
756 sub_pes->sub_st = pes->sub_st = sub_st;
757 }
758 }
759 if (st->codec->codec_id == AV_CODEC_ID_NONE && pes->stream_type == 0x82) {
760 AVStream *sub_st;
761 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
762 if (!sub_pes)
763 return AVERROR(ENOMEM);
764 memcpy(sub_pes, pes, sizeof(*sub_pes));
765 sub_st = avformat_new_stream(pes->stream, NULL);
766 if (!sub_st) {
767 av_free(sub_pes);
768 return AVERROR(ENOMEM);
769 }
770
771 sub_st->id = pes->pid;
772 av_set_pts_info(sub_st, 33, 1, 90000);
773 sub_st->priv_data = sub_pes;
774 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
775 sub_st->codec->codec_id = CODEC_ID_DTS;
776 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
777 sub_pes->sub_st = pes->sub_st = sub_st;
778 }
779
780 if (st->codec->codec_id == AV_CODEC_ID_NONE)
781 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
782 if (st->codec->codec_id == AV_CODEC_ID_NONE){
783 st->codec->codec_id = old_codec_id;
784 st->codec->codec_type= old_codec_type;
785 }
786
787 return 0;
788}
789
790static void new_pes_packet(PESContext *pes, AVPacket *pkt)
791{
792 av_init_packet(pkt);
793
794 pkt->buf = pes->buffer;
795 pkt->data = pes->buffer->data;
796 pkt->size = pes->data_index;
797
798 if(pes->total_size != MAX_PES_PAYLOAD &&
799 pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
800 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
801 pes->flags |= AV_PKT_FLAG_CORRUPT;
802 }
803 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
804
805 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
806 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
807 pkt->stream_index = pes->sub_st->index;
808 else if (pes->sub_st && pes->stream_type == 0x81 && pes->extended_stream_id == 0x72)
809 pkt->stream_index = pes->sub_st->index;
810 else
811 pkt->stream_index = pes->st->index;
812 pkt->pts = pes->pts;
813 pkt->dts = pes->dts;
814 /* store position of first TS packet of this PES packet */
815 pkt->pos = pes->ts_packet_pos;
816 pkt->flags = pes->flags;
817
818 /* reset pts values */
819 pes->pts = AV_NOPTS_VALUE;
820 pes->dts = AV_NOPTS_VALUE;
821 pes->buffer = NULL;
822 pes->data_index = 0;
823 pes->flags = 0;
824}
825
826static uint64_t get_ts64(GetBitContext *gb, int bits)
827{
828 if (get_bits_left(gb) < bits)
829 return AV_NOPTS_VALUE;
830 return get_bits64(gb, bits);
831}
832
833static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
834{
835 GetBitContext gb;
836 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
837 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
838 int dts_flag = -1, cts_flag = -1;
839 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
840
841 init_get_bits(&gb, buf, buf_size*8);
842
843 if (sl->use_au_start)
844 au_start_flag = get_bits1(&gb);
845 if (sl->use_au_end)
846 au_end_flag = get_bits1(&gb);
847 if (!sl->use_au_start && !sl->use_au_end)
848 au_start_flag = au_end_flag = 1;
849 if (sl->ocr_len > 0)
850 ocr_flag = get_bits1(&gb);
851 if (sl->use_idle)
852 idle_flag = get_bits1(&gb);
853 if (sl->use_padding)
854 padding_flag = get_bits1(&gb);
855 if (padding_flag)
856 padding_bits = get_bits(&gb, 3);
857
858 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
859 if (sl->packet_seq_num_len)
860 skip_bits_long(&gb, sl->packet_seq_num_len);
861 if (sl->degr_prior_len)
862 if (get_bits1(&gb))
863 skip_bits(&gb, sl->degr_prior_len);
864 if (ocr_flag)
865 skip_bits_long(&gb, sl->ocr_len);
866 if (au_start_flag) {
867 if (sl->use_rand_acc_pt)
868 get_bits1(&gb);
869 if (sl->au_seq_num_len > 0)
870 skip_bits_long(&gb, sl->au_seq_num_len);
871 if (sl->use_timestamps) {
872 dts_flag = get_bits1(&gb);
873 cts_flag = get_bits1(&gb);
874 }
875 }
876 if (sl->inst_bitrate_len)
877 inst_bitrate_flag = get_bits1(&gb);
878 if (dts_flag == 1)
879 dts = get_ts64(&gb, sl->timestamp_len);
880 if (cts_flag == 1)
881 cts = get_ts64(&gb, sl->timestamp_len);
882 if (sl->au_len > 0)
883 skip_bits_long(&gb, sl->au_len);
884 if (inst_bitrate_flag)
885 skip_bits_long(&gb, sl->inst_bitrate_len);
886 }
887
888 if (dts != AV_NOPTS_VALUE)
889 pes->dts = dts;
890 if (cts != AV_NOPTS_VALUE)
891 pes->pts = cts;
892
893 if (sl->timestamp_len && sl->timestamp_res)
894 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
895
896 return (get_bits_count(&gb) + 7) >> 3;
897}
898
899/* return non zero if a packet could be constructed */
900static int mpegts_push_data(MpegTSFilter *filter,
901 const uint8_t *buf, int buf_size, int is_start,
902 int64_t pos, int64_t pcr)
903{
904 PESContext *pes = filter->u.pes_filter.opaque;
905 MpegTSContext *ts = pes->ts;
906 const uint8_t *p;
907 int len, code;
908
909 if(!ts->pkt)
910 return 0;
911
912 if (pcr != -1)
913 pes->last_pcr = pcr;
914
915 if (is_start) {
916 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
917 new_pes_packet(pes, ts->pkt);
918 ts->stop_parse = 1;
919 }
920 pes->state = MPEGTS_HEADER;
921 pes->data_index = 0;
922 pes->ts_packet_pos = pos;
923 }
924 p = buf;
925 while (buf_size > 0) {
926 switch(pes->state) {
927 case MPEGTS_HEADER:
928 len = PES_START_SIZE - pes->data_index;
929 if (len > buf_size)
930 len = buf_size;
931 memcpy(pes->header + pes->data_index, p, len);
932 pes->data_index += len;
933 p += len;
934 buf_size -= len;
935 if (pes->data_index == PES_START_SIZE) {
936 /* we got all the PES or section header. We can now
937 decide */
938 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
939 pes->header[2] == 0x01) {
940 /* it must be an mpeg2 PES stream */
941 code = pes->header[3] | 0x100;
942 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
943
944 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
945 (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
946 code == 0x1be) /* padding_stream */
947 goto skip;
948
949 /* stream not present in PMT */
950 if (!pes->st) {
951 pes->st = avformat_new_stream(ts->stream, NULL);
952 if (!pes->st)
953 return AVERROR(ENOMEM);
954 pes->st->id = pes->pid;
955 mpegts_set_stream_info(pes->st, pes, 0, 0);
956 }
957
958 pes->total_size = AV_RB16(pes->header + 4);
959 /* NOTE: a zero total size means the PES size is
960 unbounded */
961 if (!pes->total_size)
962 pes->total_size = MAX_PES_PAYLOAD;
963
964 /* allocate pes buffer */
965 pes->buffer = av_buffer_alloc(pes->total_size +
966 FF_INPUT_BUFFER_PADDING_SIZE);
967 if (!pes->buffer)
968 return AVERROR(ENOMEM);
969
970 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
971 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
972 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
973 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
974 pes->state = MPEGTS_PESHEADER;
975 if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
976 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
977 pes->pid, pes->stream_type);
978 pes->st->request_probe= 1;
979 }
980 } else {
981 pes->state = MPEGTS_PAYLOAD;
982 pes->data_index = 0;
983 }
984 } else {
985 /* otherwise, it should be a table */
986 /* skip packet */
987 skip:
988 pes->state = MPEGTS_SKIP;
989 continue;
990 }
991 }
992 break;
993 /**********************************************/
994 /* PES packing parsing */
995 case MPEGTS_PESHEADER:
996 len = PES_HEADER_SIZE - pes->data_index;
997 if (len < 0)
998 return -1;
999 if (len > buf_size)
1000 len = buf_size;
1001 memcpy(pes->header + pes->data_index, p, len);
1002 pes->data_index += len;
1003 p += len;
1004 buf_size -= len;
1005 if (pes->data_index == PES_HEADER_SIZE) {
1006 pes->pes_header_size = pes->header[8] + 9;
1007 pes->state = MPEGTS_PESHEADER_FILL;
1008 }
1009 break;
1010 case MPEGTS_PESHEADER_FILL:
1011 len = pes->pes_header_size - pes->data_index;
1012 if (len < 0)
1013 return -1;
1014 if (len > buf_size)
1015 len = buf_size;
1016 memcpy(pes->header + pes->data_index, p, len);
1017 pes->data_index += len;
1018 p += len;
1019 buf_size -= len;
1020 if (pes->data_index == pes->pes_header_size) {
1021 const uint8_t *r;
1022 unsigned int flags, pes_ext, skip;
1023
1024 flags = pes->header[7];
1025 r = pes->header + 9;
1026 pes->pts = AV_NOPTS_VALUE;
1027 pes->dts = AV_NOPTS_VALUE;
1028 if ((flags & 0xc0) == 0x80) {
1029 pes->dts = pes->pts = ff_parse_pes_pts(r);
1030 r += 5;
1031 } else if ((flags & 0xc0) == 0xc0) {
1032 pes->pts = ff_parse_pes_pts(r);
1033 r += 5;
1034 pes->dts = ff_parse_pes_pts(r);
1035 r += 5;
1036 }
1037 pes->extended_stream_id = -1;
1038 if (flags & 0x01) { /* PES extension */
1039 pes_ext = *r++;
1040 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1041 skip = (pes_ext >> 4) & 0xb;
1042 skip += skip & 0x9;
1043 r += skip;
1044 if ((pes_ext & 0x41) == 0x01 &&
1045 (r + 2) <= (pes->header + pes->pes_header_size)) {
1046 /* PES extension 2 */
1047 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1048 pes->extended_stream_id = r[1];
1049 }
1050 }
1051
1052 /* we got the full header. We parse it and get the payload */
1053 pes->state = MPEGTS_PAYLOAD;
1054 pes->data_index = 0;
1055 if (pes->stream_type == 0x12 && buf_size > 0) {
1056 int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
1057 pes->pes_header_size += sl_header_bytes;
1058 p += sl_header_bytes;
1059 buf_size -= sl_header_bytes;
1060 }
1061 if (pes->stream_type == 0x15 && buf_size >= 5) {
1062 /* skip metadata access unit header */
1063 pes->pes_header_size += 5;
1064 p += 5;
1065 buf_size -= 5;
1066 }
1067 if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1068 AVProgram *p = NULL;
1069 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1070 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1071 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1072 if (f && f->type == MPEGTS_PES) {
1073 PESContext *pcrpes = f->u.pes_filter.opaque;
1074 if (pcrpes && pcrpes->last_pcr != -1 && pcrpes->st && pcrpes->st->discard != AVDISCARD_ALL) {
1075 // teletext packets do not always have correct timestamps,
1076 // the standard says they should be handled after 40.6 ms at most,
1077 // and the pcr error to this packet should be no more than 100 ms.
1078 // TODO: we should interpolate the PCR, not just use the last one
1079 int64_t pcr = pcrpes->last_pcr / 300;
1080 pes->st->pts_wrap_reference = pcrpes->st->pts_wrap_reference;
1081 pes->st->pts_wrap_behavior = pcrpes->st->pts_wrap_behavior;
1082 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1083 pes->pts = pes->dts = pcr;
1084 } else if (pes->dts > pcr + 3654 + 9000) {
1085 pes->pts = pes->dts = pcr + 3654 + 9000;
1086 }
1087 break;
1088 }
1089 }
1090 }
1091 }
1092 }
1093 }
1094 break;
1095 case MPEGTS_PAYLOAD:
1096 if (buf_size > 0 && pes->buffer) {
1097 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
1098 new_pes_packet(pes, ts->pkt);
1099 pes->total_size = MAX_PES_PAYLOAD;
1100 pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
1101 if (!pes->buffer)
1102 return AVERROR(ENOMEM);
1103 ts->stop_parse = 1;
1104 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
1105 // pes packet size is < ts size packet and pes data is padded with 0xff
1106 // not sure if this is legal in ts but see issue #2392
1107 buf_size = pes->total_size;
1108 }
1109 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1110 pes->data_index += buf_size;
1111 }
1112 buf_size = 0;
1113 /* emit complete packets with known packet size
1114 * decreases demuxer delay for infrequent packets like subtitles from
1115 * a couple of seconds to milliseconds for properly muxed files.
1116 * total_size is the number of bytes following pes_packet_length
1117 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1118 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1119 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1120 ts->stop_parse = 1;
1121 new_pes_packet(pes, ts->pkt);
1122 }
1123 break;
1124 case MPEGTS_SKIP:
1125 buf_size = 0;
1126 break;
1127 }
1128 }
1129
1130 return 0;
1131}
1132
1133static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1134{
1135 MpegTSFilter *tss;
1136 PESContext *pes;
1137
1138 /* if no pid found, then add a pid context */
1139 pes = av_mallocz(sizeof(PESContext));
1140 if (!pes)
1141 return 0;
1142 pes->ts = ts;
1143 pes->stream = ts->stream;
1144 pes->pid = pid;
1145 pes->pcr_pid = pcr_pid;
1146 pes->state = MPEGTS_SKIP;
1147 pes->pts = AV_NOPTS_VALUE;
1148 pes->dts = AV_NOPTS_VALUE;
1149 pes->last_pcr = -1;
1150 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1151 if (!tss) {
1152 av_free(pes);
1153 return 0;
1154 }
1155 return pes;
1156}
1157
1158#define MAX_LEVEL 4
1159typedef struct {
1160 AVFormatContext *s;
1161 AVIOContext pb;
1162 Mp4Descr *descr;
1163 Mp4Descr *active_descr;
1164 int descr_count;
1165 int max_descr_count;
1166 int level;
1167} MP4DescrParseContext;
1168
1169static int init_MP4DescrParseContext(
1170 MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1171 unsigned size, Mp4Descr *descr, int max_descr_count)
1172{
1173 int ret;
1174 if (size > (1<<30))
1175 return AVERROR_INVALIDDATA;
1176
1177 if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1178 NULL, NULL, NULL, NULL)) < 0)
1179 return ret;
1180
1181 d->s = s;
1182 d->level = 0;
1183 d->descr_count = 0;
1184 d->descr = descr;
1185 d->active_descr = NULL;
1186 d->max_descr_count = max_descr_count;
1187
1188 return 0;
1189}
1190
1191static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1192 int64_t new_off = avio_tell(pb);
1193 (*len) -= new_off - *off;
1194 *off = new_off;
1195}
1196
1197static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1198 int target_tag);
1199
1200static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1201{
1202 while (len > 0) {
1203 if (parse_mp4_descr(d, off, len, 0) < 0)
1204 return -1;
1205 update_offsets(&d->pb, &off, &len);
1206 }
1207 return 0;
1208}
1209
1210static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1211{
1212 avio_rb16(&d->pb); // ID
1213 avio_r8(&d->pb);
1214 avio_r8(&d->pb);
1215 avio_r8(&d->pb);
1216 avio_r8(&d->pb);
1217 avio_r8(&d->pb);
1218 update_offsets(&d->pb, &off, &len);
1219 return parse_mp4_descr_arr(d, off, len);
1220}
1221
1222static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1223{
1224 int id_flags;
1225 if (len < 2)
1226 return 0;
1227 id_flags = avio_rb16(&d->pb);
1228 if (!(id_flags & 0x0020)) { //URL_Flag
1229 update_offsets(&d->pb, &off, &len);
1230 return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1231 } else {
1232 return 0;
1233 }
1234}
1235
1236static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1237{
1238 int es_id = 0;
1239 if (d->descr_count >= d->max_descr_count)
1240 return -1;
1241 ff_mp4_parse_es_descr(&d->pb, &es_id);
1242 d->active_descr = d->descr + (d->descr_count++);
1243
1244 d->active_descr->es_id = es_id;
1245 update_offsets(&d->pb, &off, &len);
1246 parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1247 update_offsets(&d->pb, &off, &len);
1248 if (len > 0)
1249 parse_mp4_descr(d, off, len, MP4SLDescrTag);
1250 d->active_descr = NULL;
1251 return 0;
1252}
1253
1254static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1255{
1256 Mp4Descr *descr = d->active_descr;
1257 if (!descr)
1258 return -1;
1259 d->active_descr->dec_config_descr = av_malloc(len);
1260 if (!descr->dec_config_descr)
1261 return AVERROR(ENOMEM);
1262 descr->dec_config_descr_len = len;
1263 avio_read(&d->pb, descr->dec_config_descr, len);
1264 return 0;
1265}
1266
1267static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1268{
1269 Mp4Descr *descr = d->active_descr;
1270 int predefined;
1271 if (!descr)
1272 return -1;
1273
1274 predefined = avio_r8(&d->pb);
1275 if (!predefined) {
1276 int lengths;
1277 int flags = avio_r8(&d->pb);
1278 descr->sl.use_au_start = !!(flags & 0x80);
1279 descr->sl.use_au_end = !!(flags & 0x40);
1280 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1281 descr->sl.use_padding = !!(flags & 0x08);
1282 descr->sl.use_timestamps = !!(flags & 0x04);
1283 descr->sl.use_idle = !!(flags & 0x02);
1284 descr->sl.timestamp_res = avio_rb32(&d->pb);
1285 avio_rb32(&d->pb);
1286 descr->sl.timestamp_len = avio_r8(&d->pb);
1287 descr->sl.ocr_len = avio_r8(&d->pb);
1288 descr->sl.au_len = avio_r8(&d->pb);
1289 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1290 lengths = avio_rb16(&d->pb);
1291 descr->sl.degr_prior_len = lengths >> 12;
1292 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1293 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1294 } else {
1295 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1296 }
1297 return 0;
1298}
1299
1300static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1301 int target_tag) {
1302 int tag;
1303 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1304 update_offsets(&d->pb, &off, &len);
1305 if (len < 0 || len1 > len || len1 <= 0) {
1306 av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1307 return -1;
1308 }
1309
1310 if (d->level++ >= MAX_LEVEL) {
1311 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1312 goto done;
1313 }
1314
1315 if (target_tag && tag != target_tag) {
1316 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1317 goto done;
1318 }
1319
1320 switch (tag) {
1321 case MP4IODescrTag:
1322 parse_MP4IODescrTag(d, off, len1);
1323 break;
1324 case MP4ODescrTag:
1325 parse_MP4ODescrTag(d, off, len1);
1326 break;
1327 case MP4ESDescrTag:
1328 parse_MP4ESDescrTag(d, off, len1);
1329 break;
1330 case MP4DecConfigDescrTag:
1331 parse_MP4DecConfigDescrTag(d, off, len1);
1332 break;
1333 case MP4SLDescrTag:
1334 parse_MP4SLDescrTag(d, off, len1);
1335 break;
1336 }
1337
1338done:
1339 d->level--;
1340 avio_seek(&d->pb, off + len1, SEEK_SET);
1341 return 0;
1342}
1343
1344static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1345 Mp4Descr *descr, int *descr_count, int max_descr_count)
1346{
1347 MP4DescrParseContext d;
1348 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1349 return -1;
1350
1351 parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1352
1353 *descr_count = d.descr_count;
1354 return 0;
1355}
1356
1357static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1358 Mp4Descr *descr, int *descr_count, int max_descr_count)
1359{
1360 MP4DescrParseContext d;
1361 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1362 return -1;
1363
1364 parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1365
1366 *descr_count = d.descr_count;
1367 return 0;
1368}
1369
1370static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1371{
1372 MpegTSContext *ts = filter->u.section_filter.opaque;
1373 SectionHeader h;
1374 const uint8_t *p, *p_end;
1375 AVIOContext pb;
1376 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1377 int mp4_descr_count = 0;
1378 int i, pid;
1379 AVFormatContext *s = ts->stream;
1380
1381 p_end = section + section_len - 4;
1382 p = section;
1383 if (parse_section_header(&h, &p, p_end) < 0)
1384 return;
1385 if (h.tid != M4OD_TID)
1386 return;
1387
1388 mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1389
1390 for (pid = 0; pid < NB_PID_MAX; pid++) {
1391 if (!ts->pids[pid])
1392 continue;
1393 for (i = 0; i < mp4_descr_count; i++) {
1394 PESContext *pes;
1395 AVStream *st;
1396 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1397 continue;
1398 if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1399 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1400 continue;
1401 }
1402 pes = ts->pids[pid]->u.pes_filter.opaque;
1403 st = pes->st;
1404 if (!st) {
1405 continue;
1406 }
1407
1408 pes->sl = mp4_descr[i].sl;
1409
1410 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1411 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1412 ff_mp4_read_dec_config_descr(s, st, &pb);
1413 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1414 st->codec->extradata_size > 0)
1415 st->need_parsing = 0;
1416 if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1417 st->codec->extradata_size > 0)
1418 st->need_parsing = 0;
1419
1420 if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1421 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1422 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1423 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1424 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1425 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1426 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1427 }
1428 }
1429 }
1430 for (i = 0; i < mp4_descr_count; i++)
1431 av_free(mp4_descr[i].dec_config_descr);
1432}
1433
1434int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1435 const uint8_t **pp, const uint8_t *desc_list_end,
1436 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1437 MpegTSContext *ts)
1438{
1439 const uint8_t *desc_end;
1440 int desc_len, desc_tag, desc_es_id;
1441 char language[252];
1442 int i;
1443
1444 desc_tag = get8(pp, desc_list_end);
1445 if (desc_tag < 0)
1446 return -1;
1447 desc_len = get8(pp, desc_list_end);
1448 if (desc_len < 0)
1449 return -1;
1450 desc_end = *pp + desc_len;
1451 if (desc_end > desc_list_end)
1452 return -1;
1453
1454 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1455
1456 if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1457 stream_type == STREAM_TYPE_PRIVATE_DATA)
1458 mpegts_find_stream_type(st, desc_tag, DESC_types);
1459
1460 switch(desc_tag) {
1461 case 0x1E: /* SL descriptor */
1462 desc_es_id = get16(pp, desc_end);
1463 if (ts && ts->pids[pid])
1464 ts->pids[pid]->es_id = desc_es_id;
1465 for (i = 0; i < mp4_descr_count; i++)
1466 if (mp4_descr[i].dec_config_descr_len &&
1467 mp4_descr[i].es_id == desc_es_id) {
1468 AVIOContext pb;
1469 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1470 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1471 ff_mp4_read_dec_config_descr(fc, st, &pb);
1472 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1473 st->codec->extradata_size > 0)
1474 st->need_parsing = 0;
1475 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1476 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1477 }
1478 break;
1479 case 0x1F: /* FMC descriptor */
1480 get16(pp, desc_end);
1481 if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1482 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1483 AVIOContext pb;
1484 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1485 mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1486 ff_mp4_read_dec_config_descr(fc, st, &pb);
1487 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1488 st->codec->extradata_size > 0){
1489 st->request_probe= st->need_parsing = 0;
1490 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
1491 }
1492 }
1493 break;
1494 case 0x56: /* DVB teletext descriptor */
1495 language[0] = get8(pp, desc_end);
1496 language[1] = get8(pp, desc_end);
1497 language[2] = get8(pp, desc_end);
1498 language[3] = 0;
1499 av_dict_set(&st->metadata, "language", language, 0);
1500 break;
1501 case 0x59: /* subtitling descriptor */
1502 language[0] = get8(pp, desc_end);
1503 language[1] = get8(pp, desc_end);
1504 language[2] = get8(pp, desc_end);
1505 language[3] = 0;
1506 /* hearing impaired subtitles detection */
1507 switch(get8(pp, desc_end)) {
1508 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1509 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1510 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1511 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1512 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1513 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1514 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1515 break;
1516 }
1517 if (st->codec->extradata) {
1518 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1519 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1520 } else {
1521 if (!ff_alloc_extradata(st->codec, 4)) {
1522 memcpy(st->codec->extradata, *pp, 4);
1523 }
1524 }
1525 *pp += 4;
1526 av_dict_set(&st->metadata, "language", language, 0);
1527 break;
1528 case 0x0a: /* ISO 639 language descriptor */
1529 for (i = 0; i + 4 <= desc_len; i += 4) {
1530 language[i + 0] = get8(pp, desc_end);
1531 language[i + 1] = get8(pp, desc_end);
1532 language[i + 2] = get8(pp, desc_end);
1533 language[i + 3] = ',';
1534 switch (get8(pp, desc_end)) {
1535 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1536 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1537 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1538 }
1539 }
1540 if (i) {
1541 language[i - 1] = 0;
1542 av_dict_set(&st->metadata, "language", language, 0);
1543 }
1544 break;
1545 case 0x05: /* registration descriptor */
1546 st->codec->codec_tag = bytestream_get_le32(pp);
1547 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1548 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1549 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1550 break;
1551 case 0x52: /* stream identifier descriptor */
1552 st->stream_identifier = 1 + get8(pp, desc_end);
1553 break;
1554 case 0x26: /* metadata descriptor */
1555 if (get16(pp, desc_end) == 0xFFFF)
1556 *pp += 4;
1557 if (get8(pp, desc_end) == 0xFF) {
1558 st->codec->codec_tag = bytestream_get_le32(pp);
1559 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1560 mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
1561 }
1562 break;
1563 default:
1564 break;
1565 }
1566 *pp = desc_end;
1567 return 0;
1568}
1569
1570static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1571{
1572 MpegTSContext *ts = filter->u.section_filter.opaque;
1573 SectionHeader h1, *h = &h1;
1574 PESContext *pes;
1575 AVStream *st;
1576 const uint8_t *p, *p_end, *desc_list_end;
1577 int program_info_length, pcr_pid, pid, stream_type;
1578 int desc_list_len;
1579 uint32_t prog_reg_desc = 0; /* registration descriptor */
1580
1581 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1582 int mp4_descr_count = 0;
1583 int i;
1584
1585 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1586 hex_dump_debug(ts->stream, section, section_len);
1587
1588 p_end = section + section_len - 4;
1589 p = section;
1590 if (parse_section_header(h, &p, p_end) < 0)
1591 return;
1592
1593 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1594 h->id, h->sec_num, h->last_sec_num);
1595
1596 if (h->tid != PMT_TID)
1597 return;
1598
1599 clear_program(ts, h->id);
1600 pcr_pid = get16(&p, p_end);
1601 if (pcr_pid < 0)
1602 return;
1603 pcr_pid &= 0x1fff;
1604 add_pid_to_pmt(ts, h->id, pcr_pid);
1605 set_pcr_pid(ts->stream, h->id, pcr_pid);
1606
1607 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1608
1609 program_info_length = get16(&p, p_end);
1610 if (program_info_length < 0)
1611 return;
1612 program_info_length &= 0xfff;
1613 while(program_info_length >= 2) {
1614 uint8_t tag, len;
1615 tag = get8(&p, p_end);
1616 len = get8(&p, p_end);
1617
1618 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1619
1620 if(len > program_info_length - 2)
1621 //something else is broken, exit the program_descriptors_loop
1622 break;
1623 program_info_length -= len + 2;
1624 if (tag == 0x1d) { // IOD descriptor
1625 get8(&p, p_end); // scope
1626 get8(&p, p_end); // label
1627 len -= 2;
1628 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1629 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1630 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1631 prog_reg_desc = bytestream_get_le32(&p);
1632 len -= 4;
1633 }
1634 p += len;
1635 }
1636 p += program_info_length;
1637 if (p >= p_end)
1638 goto out;
1639
1640 // stop parsing after pmt, we found header
1641 if (!ts->stream->nb_streams)
1642 ts->stop_parse = 2;
1643
1644 for(;;) {
1645 st = 0;
1646 pes = NULL;
1647 stream_type = get8(&p, p_end);
1648 if (stream_type < 0)
1649 break;
1650 pid = get16(&p, p_end);
1651 if (pid < 0)
1652 break;
1653 pid &= 0x1fff;
1654 if (pid == ts->current_pid)
1655 break;
1656
1657 /* now create stream */
1658 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1659 pes = ts->pids[pid]->u.pes_filter.opaque;
1660 if (!pes->st) {
1661 pes->st = avformat_new_stream(pes->stream, NULL);
1662 if (!pes->st)
1663 goto out;
1664 pes->st->id = pes->pid;
1665 }
1666 st = pes->st;
1667 } else if (stream_type != 0x13) {
1668 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1669 pes = add_pes_stream(ts, pid, pcr_pid);
1670 if (pes) {
1671 st = avformat_new_stream(pes->stream, NULL);
1672 if (!st)
1673 goto out;
1674 st->id = pes->pid;
1675 }
1676 } else {
1677 int idx = ff_find_stream_index(ts->stream, pid);
1678 if (idx >= 0) {
1679 st = ts->stream->streams[idx];
1680 } else {
1681 st = avformat_new_stream(ts->stream, NULL);
1682 if (!st)
1683 goto out;
1684 st->id = pid;
1685 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1686 }
1687 }
1688
1689 if (!st)
1690 goto out;
1691
1692 if (pes && !pes->stream_type)
1693 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1694
1695 add_pid_to_pmt(ts, h->id, pid);
1696
1697 ff_program_add_stream_index(ts->stream, h->id, st->index);
1698
1699 desc_list_len = get16(&p, p_end);
1700 if (desc_list_len < 0)
1701 break;
1702 desc_list_len &= 0xfff;
1703 desc_list_end = p + desc_list_len;
1704 if (desc_list_end > p_end)
1705 break;
1706 for(;;) {
1707 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1708 mp4_descr, mp4_descr_count, pid, ts) < 0)
1709 break;
1710
1711 if (pes && prog_reg_desc == AV_RL32("HDMV") && (stream_type == 0x83 || stream_type == 0x81) && pes->sub_st) {
1712 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1713 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1714 }
1715 }
1716 p = desc_list_end;
1717 }
1718
1719 out:
1720 for (i = 0; i < mp4_descr_count; i++)
1721 av_free(mp4_descr[i].dec_config_descr);
1722}
1723
1724static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1725{
1726 MpegTSContext *ts = filter->u.section_filter.opaque;
1727 SectionHeader h1, *h = &h1;
1728 const uint8_t *p, *p_end;
1729 int sid, pmt_pid;
1730 AVProgram *program;
1731
1732 av_dlog(ts->stream, "PAT:\n");
1733 hex_dump_debug(ts->stream, section, section_len);
1734
1735 p_end = section + section_len - 4;
1736 p = section;
1737 if (parse_section_header(h, &p, p_end) < 0)
1738 return;
1739 if (h->tid != PAT_TID)
1740 return;
1741
1742 ts->stream->ts_id = h->id;
1743
1744 clear_programs(ts);
1745 for(;;) {
1746 sid = get16(&p, p_end);
1747 if (sid < 0)
1748 break;
1749 pmt_pid = get16(&p, p_end);
1750 if (pmt_pid < 0)
1751 break;
1752 pmt_pid &= 0x1fff;
1753
1754 if (pmt_pid == ts->current_pid)
1755 break;
1756
1757 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1758
1759 if (sid == 0x0000) {
1760 /* NIT info */
1761 } else {
1762 MpegTSFilter *fil = ts->pids[pmt_pid];
1763 program = av_new_program(ts->stream, sid);
1764 program->program_num = sid;
1765 program->pmt_pid = pmt_pid;
1766 if (fil)
1767 if ( fil->type != MPEGTS_SECTION
1768 || fil->pid != pmt_pid
1769 || fil->u.section_filter.section_cb != pmt_cb)
1770 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1771
1772 if (!ts->pids[pmt_pid])
1773 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1774 add_pat_entry(ts, sid);
1775 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1776 add_pid_to_pmt(ts, sid, pmt_pid);
1777 }
1778 }
1779
1780 if (sid < 0) {
1781 int i,j;
1782 for (j=0; j<ts->stream->nb_programs; j++) {
1783 for (i=0; i<ts->nb_prg; i++)
1784 if (ts->prg[i].id == ts->stream->programs[j]->id)
1785 break;
1786 if (i==ts->nb_prg)
1787 clear_avprogram(ts, ts->stream->programs[j]->id);
1788 }
1789 }
1790}
1791
1792static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1793{
1794 MpegTSContext *ts = filter->u.section_filter.opaque;
1795 SectionHeader h1, *h = &h1;
1796 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1797 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1798 char *name, *provider_name;
1799
1800 av_dlog(ts->stream, "SDT:\n");
1801 hex_dump_debug(ts->stream, section, section_len);
1802
1803 p_end = section + section_len - 4;
1804 p = section;
1805 if (parse_section_header(h, &p, p_end) < 0)
1806 return;
1807 if (h->tid != SDT_TID)
1808 return;
1809 onid = get16(&p, p_end);
1810 if (onid < 0)
1811 return;
1812 val = get8(&p, p_end);
1813 if (val < 0)
1814 return;
1815 for(;;) {
1816 sid = get16(&p, p_end);
1817 if (sid < 0)
1818 break;
1819 val = get8(&p, p_end);
1820 if (val < 0)
1821 break;
1822 desc_list_len = get16(&p, p_end);
1823 if (desc_list_len < 0)
1824 break;
1825 desc_list_len &= 0xfff;
1826 desc_list_end = p + desc_list_len;
1827 if (desc_list_end > p_end)
1828 break;
1829 for(;;) {
1830 desc_tag = get8(&p, desc_list_end);
1831 if (desc_tag < 0)
1832 break;
1833 desc_len = get8(&p, desc_list_end);
1834 desc_end = p + desc_len;
1835 if (desc_end > desc_list_end)
1836 break;
1837
1838 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1839 desc_tag, desc_len);
1840
1841 switch(desc_tag) {
1842 case 0x48:
1843 service_type = get8(&p, p_end);
1844 if (service_type < 0)
1845 break;
1846 provider_name = getstr8(&p, p_end);
1847 if (!provider_name)
1848 break;
1849 name = getstr8(&p, p_end);
1850 if (name) {
1851 AVProgram *program = av_new_program(ts->stream, sid);
1852 if(program) {
1853 av_dict_set(&program->metadata, "service_name", name, 0);
1854 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1855 }
1856 }
1857 av_free(name);
1858 av_free(provider_name);
1859 break;
1860 default:
1861 break;
1862 }
1863 p = desc_end;
1864 }
1865 p = desc_list_end;
1866 }
1867}
1868
1869static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1870 const uint8_t *packet);
1871
1872/* handle one TS packet */
1873static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1874{
1875 AVFormatContext *s = ts->stream;
1876 MpegTSFilter *tss;
1877 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1878 has_adaptation, has_payload;
1879 const uint8_t *p, *p_end;
1880 int64_t pos;
1881
1882 pid = AV_RB16(packet + 1) & 0x1fff;
1883 if(pid && discard_pid(ts, pid))
1884 return 0;
1885 is_start = packet[1] & 0x40;
1886 tss = ts->pids[pid];
1887 if (ts->auto_guess && tss == NULL && is_start) {
1888 add_pes_stream(ts, pid, -1);
1889 tss = ts->pids[pid];
1890 }
1891 if (!tss)
1892 return 0;
1893 ts->current_pid = pid;
1894
1895 afc = (packet[3] >> 4) & 3;
1896 if (afc == 0) /* reserved value */
1897 return 0;
1898 has_adaptation = afc & 2;
1899 has_payload = afc & 1;
1900 is_discontinuity = has_adaptation
1901 && packet[4] != 0 /* with length > 0 */
1902 && (packet[5] & 0x80); /* and discontinuity indicated */
1903
1904 /* continuity check (currently not used) */
1905 cc = (packet[3] & 0xf);
1906 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1907 cc_ok = pid == 0x1FFF // null packet PID
1908 || is_discontinuity
1909 || tss->last_cc < 0
1910 || expected_cc == cc;
1911
1912 tss->last_cc = cc;
1913 if (!cc_ok) {
1914 av_log(ts->stream, AV_LOG_DEBUG,
1915 "Continuity check failed for pid %d expected %d got %d\n",
1916 pid, expected_cc, cc);
1917 if(tss->type == MPEGTS_PES) {
1918 PESContext *pc = tss->u.pes_filter.opaque;
1919 pc->flags |= AV_PKT_FLAG_CORRUPT;
1920 }
1921 }
1922
1923 if (!has_payload)
1924 return 0;
1925 p = packet + 4;
1926 if (has_adaptation) {
1927 /* skip adaptation field */
1928 p += p[0] + 1;
1929 }
1930 /* if past the end of packet, ignore */
1931 p_end = packet + TS_PACKET_SIZE;
1932 if (p >= p_end)
1933 return 0;
1934
1935 pos = avio_tell(ts->stream->pb);
1936 if (pos >= 0) {
1937 av_assert0(pos >= TS_PACKET_SIZE);
1938 ts->pos47_full = pos - TS_PACKET_SIZE;
1939 }
1940
1941 if (tss->type == MPEGTS_SECTION) {
1942 if (is_start) {
1943 /* pointer field present */
1944 len = *p++;
1945 if (p + len > p_end)
1946 return 0;
1947 if (len && cc_ok) {
1948 /* write remaining section bytes */
1949 write_section_data(s, tss,
1950 p, len, 0);
1951 /* check whether filter has been closed */
1952 if (!ts->pids[pid])
1953 return 0;
1954 }
1955 p += len;
1956 if (p < p_end) {
1957 write_section_data(s, tss,
1958 p, p_end - p, 1);
1959 }
1960 } else {
1961 if (cc_ok) {
1962 write_section_data(s, tss,
1963 p, p_end - p, 0);
1964 }
1965 }
1966 } else {
1967 int ret;
1968 int64_t pcr = -1;
1969 int64_t pcr_h;
1970 int pcr_l;
1971 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
1972 pcr = pcr_h * 300 + pcr_l;
1973 // Note: The position here points actually behind the current packet.
1974 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1975 pos - ts->raw_packet_size, pcr)) < 0)
1976 return ret;
1977 }
1978
1979 return 0;
1980}
1981
1982static void reanalyze(MpegTSContext *ts) {
1983 AVIOContext *pb = ts->stream->pb;
1984 int64_t pos = avio_tell(pb);
1985 if(pos < 0)
1986 return;
1987 pos -= ts->pos47_full;
1988 if (pos == TS_PACKET_SIZE) {
1989 ts->size_stat[0] ++;
1990 } else if (pos == TS_DVHS_PACKET_SIZE) {
1991 ts->size_stat[1] ++;
1992 } else if (pos == TS_FEC_PACKET_SIZE) {
1993 ts->size_stat[2] ++;
1994 }
1995
1996 ts->size_stat_count ++;
1997 if(ts->size_stat_count > SIZE_STAT_THRESHOLD) {
1998 int newsize = 0;
1999 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2000 newsize = TS_PACKET_SIZE;
2001 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2002 newsize = TS_DVHS_PACKET_SIZE;
2003 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2004 newsize = TS_FEC_PACKET_SIZE;
2005 }
2006 if (newsize && newsize != ts->raw_packet_size) {
2007 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2008 ts->raw_packet_size = newsize;
2009 }
2010 ts->size_stat_count = 0;
2011 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2012 }
2013}
2014
2015/* XXX: try to find a better synchro over several packets (use
2016 get_packet_size() ?) */
2017static int mpegts_resync(AVFormatContext *s)
2018{
2019 AVIOContext *pb = s->pb;
2020 int c, i;
2021
2022 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
2023 c = avio_r8(pb);
2024 if (url_feof(pb))
2025 return -1;
2026 if (c == 0x47) {
2027 avio_seek(pb, -1, SEEK_CUR);
2028 reanalyze(s->priv_data);
2029 return 0;
2030 }
2031 }
2032 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
2033 /* no sync found */
2034 return -1;
2035}
2036
2037/* return -1 if error or EOF. Return 0 if OK. */
2038static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
2039{
2040 AVIOContext *pb = s->pb;
2041 int len;
2042
2043 for(;;) {
2044 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2045 if (len != TS_PACKET_SIZE)
2046 return len < 0 ? len : AVERROR_EOF;
2047 /* check packet sync byte */
2048 if ((*data)[0] != 0x47) {
2049 /* find a new packet start */
2050 avio_seek(pb, -raw_packet_size, SEEK_CUR);
2051 if (mpegts_resync(s) < 0)
2052 return AVERROR(EAGAIN);
2053 else
2054 continue;
2055 } else {
2056 break;
2057 }
2058 }
2059 return 0;
2060}
2061
2062static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2063{
2064 AVIOContext *pb = s->pb;
2065 int skip = raw_packet_size - TS_PACKET_SIZE;
2066 if (skip > 0)
2067 avio_skip(pb, skip);
2068}
2069
2070static int handle_packets(MpegTSContext *ts, int nb_packets)
2071{
2072 AVFormatContext *s = ts->stream;
2073 uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
2074 const uint8_t *data;
2075 int packet_num, ret = 0;
2076
2077 if (avio_tell(s->pb) != ts->last_pos) {
2078 int i;
2079 av_dlog(ts->stream, "Skipping after seek\n");
2080 /* seek detected, flush pes buffer */
2081 for (i = 0; i < NB_PID_MAX; i++) {
2082 if (ts->pids[i]) {
2083 if (ts->pids[i]->type == MPEGTS_PES) {
2084 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2085 av_buffer_unref(&pes->buffer);
2086 pes->data_index = 0;
2087 pes->state = MPEGTS_SKIP; /* skip until pes header */
2088 pes->last_pcr = -1;
2089 }
2090 ts->pids[i]->last_cc = -1;
2091 }
2092 }
2093 }
2094
2095 ts->stop_parse = 0;
2096 packet_num = 0;
2097 memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2098 for(;;) {
2099 packet_num++;
2100 if (nb_packets != 0 && packet_num >= nb_packets ||
2101 ts->stop_parse > 1) {
2102 ret = AVERROR(EAGAIN);
2103 break;
2104 }
2105 if (ts->stop_parse > 0)
2106 break;
2107
2108 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2109 if (ret != 0)
2110 break;
2111 ret = handle_packet(ts, data);
2112 finished_reading_packet(s, ts->raw_packet_size);
2113 if (ret != 0)
2114 break;
2115 }
2116 ts->last_pos = avio_tell(s->pb);
2117 return ret;
2118}
2119
2120static int mpegts_probe(AVProbeData *p)
2121{
2122 const int size= p->buf_size;
2123 int maxscore=0;
2124 int sumscore=0;
2125 int i;
2126 int check_count= size / TS_FEC_PACKET_SIZE;
2127#define CHECK_COUNT 10
2128#define CHECK_BLOCK 100
2129
2130 if (check_count < CHECK_COUNT)
2131 return -1;
2132
2133 for (i=0; i<check_count; i+=CHECK_BLOCK){
2134 int left = FFMIN(check_count - i, CHECK_BLOCK);
2135 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
2136 int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
2137 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
2138 score = FFMAX3(score, dvhs_score, fec_score);
2139 sumscore += score;
2140 maxscore = FFMAX(maxscore, score);
2141 }
2142
2143 sumscore = sumscore*CHECK_COUNT/check_count;
2144 maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
2145
2146 av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2147
2148 if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2149 else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2150 else return -1;
2151}
2152
2153/* return the 90kHz PCR and the extension for the 27MHz PCR. return
2154 (-1) if not available */
2155static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2156 const uint8_t *packet)
2157{
2158 int afc, len, flags;
2159 const uint8_t *p;
2160 unsigned int v;
2161
2162 afc = (packet[3] >> 4) & 3;
2163 if (afc <= 1)
2164 return -1;
2165 p = packet + 4;
2166 len = p[0];
2167 p++;
2168 if (len == 0)
2169 return -1;
2170 flags = *p++;
2171 len--;
2172 if (!(flags & 0x10))
2173 return -1;
2174 if (len < 6)
2175 return -1;
2176 v = AV_RB32(p);
2177 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2178 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2179 return 0;
2180}
2181
2182static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2183
2184 /* NOTE: We attempt to seek on non-seekable files as well, as the
2185 * probe buffer usually is big enough. Only warn if the seek failed
2186 * on files where the seek should work. */
2187 if (avio_seek(pb, pos, SEEK_SET) < 0)
2188 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2189}
2190
2191static int mpegts_read_header(AVFormatContext *s)
2192{
2193 MpegTSContext *ts = s->priv_data;
2194 AVIOContext *pb = s->pb;
2195 uint8_t buf[8*1024]={0};
2196 int len;
2197 int64_t pos;
2198
2199 ts->first_pcrscr=AV_NOPTS_VALUE;
2200
2201 ffio_ensure_seekback(pb, s->probesize);
2202
2203 /* read the first 8192 bytes to get packet size */
2204 pos = avio_tell(pb);
2205 len = avio_read(pb, buf, sizeof(buf));
2206 ts->raw_packet_size = get_packet_size(buf, len);
2207 if (ts->raw_packet_size <= 0) {
2208 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2209 ts->raw_packet_size = TS_PACKET_SIZE;
2210 }
2211 ts->stream = s;
2212 ts->auto_guess = 0;
2213
2214 if (s->iformat == &ff_mpegts_demuxer) {
2215 /* normal demux */
2216
2217 /* first do a scan to get all the services */
2218 seek_back(s, pb, pos);
2219
2220 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2221
2222 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2223
2224 handle_packets(ts, s->probesize / ts->raw_packet_size);
2225 /* if could not find service, enable auto_guess */
2226
2227 ts->auto_guess = 1;
2228
2229 av_dlog(ts->stream, "tuning done\n");
2230
2231 s->ctx_flags |= AVFMTCTX_NOHEADER;
2232 } else {
2233 AVStream *st;
2234 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2235 int64_t pcrs[2], pcr_h;
2236 int packet_count[2];
2237 uint8_t packet[TS_PACKET_SIZE];
2238 const uint8_t *data;
2239
2240 /* only read packets */
2241
2242 st = avformat_new_stream(s, NULL);
2243 if (!st)
2244 goto fail;
2245 avpriv_set_pts_info(st, 60, 1, 27000000);
2246 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2247 st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2248
2249 /* we iterate until we find two PCRs to estimate the bitrate */
2250 pcr_pid = -1;
2251 nb_pcrs = 0;
2252 nb_packets = 0;
2253 for(;;) {
2254 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2255 if (ret < 0)
2256 goto fail;
2257 pid = AV_RB16(data + 1) & 0x1fff;
2258 if ((pcr_pid == -1 || pcr_pid == pid) &&
2259 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2260 finished_reading_packet(s, ts->raw_packet_size);
2261 pcr_pid = pid;
2262 packet_count[nb_pcrs] = nb_packets;
2263 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2264 nb_pcrs++;
2265 if (nb_pcrs >= 2)
2266 break;
2267 } else {
2268 finished_reading_packet(s, ts->raw_packet_size);
2269 }
2270 nb_packets++;
2271 }
2272
2273 /* NOTE1: the bitrate is computed without the FEC */
2274 /* NOTE2: it is only the bitrate of the start of the stream */
2275 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2276 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2277 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2278 st->codec->bit_rate = s->bit_rate;
2279 st->start_time = ts->cur_pcr;
2280 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2281 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2282 }
2283
2284 seek_back(s, pb, pos);
2285 return 0;
2286 fail:
2287 return -1;
2288}
2289
2290#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2291
2292static int mpegts_raw_read_packet(AVFormatContext *s,
2293 AVPacket *pkt)
2294{
2295 MpegTSContext *ts = s->priv_data;
2296 int ret, i;
2297 int64_t pcr_h, next_pcr_h, pos;
2298 int pcr_l, next_pcr_l;
2299 uint8_t pcr_buf[12];
2300 const uint8_t *data;
2301
2302 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2303 return AVERROR(ENOMEM);
2304 pkt->pos= avio_tell(s->pb);
2305 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2306 if (ret < 0) {
2307 av_free_packet(pkt);
2308 return ret;
2309 }
2310 if (data != pkt->data)
2311 memcpy(pkt->data, data, ts->raw_packet_size);
2312 finished_reading_packet(s, ts->raw_packet_size);
2313 if (ts->mpeg2ts_compute_pcr) {
2314 /* compute exact PCR for each packet */
2315 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2316 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2317 pos = avio_tell(s->pb);
2318 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2319 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2320 avio_read(s->pb, pcr_buf, 12);
2321 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2322 /* XXX: not precise enough */
2323 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2324 (i + 1);
2325 break;
2326 }
2327 }
2328 avio_seek(s->pb, pos, SEEK_SET);
2329 /* no next PCR found: we use previous increment */
2330 ts->cur_pcr = pcr_h * 300 + pcr_l;
2331 }
2332 pkt->pts = ts->cur_pcr;
2333 pkt->duration = ts->pcr_incr;
2334 ts->cur_pcr += ts->pcr_incr;
2335 }
2336 pkt->stream_index = 0;
2337 return 0;
2338}
2339
2340static int mpegts_read_packet(AVFormatContext *s,
2341 AVPacket *pkt)
2342{
2343 MpegTSContext *ts = s->priv_data;
2344 int ret, i;
2345
2346 pkt->size = -1;
2347 ts->pkt = pkt;
2348 ret = handle_packets(ts, 0);
2349 if (ret < 0) {
2350 av_free_packet(ts->pkt);
2351 /* flush pes data left */
2352 for (i = 0; i < NB_PID_MAX; i++) {
2353 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2354 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2355 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2356 new_pes_packet(pes, pkt);
2357 pes->state = MPEGTS_SKIP;
2358 ret = 0;
2359 break;
2360 }
2361 }
2362 }
2363 }
2364
2365 if (!ret && pkt->size < 0)
2366 ret = AVERROR(EINTR);
2367 return ret;
2368}
2369
2370static void mpegts_free(MpegTSContext *ts)
2371{
2372 int i;
2373
2374 clear_programs(ts);
2375
2376 for(i=0;i<NB_PID_MAX;i++)
2377 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2378}
2379
2380static int mpegts_read_close(AVFormatContext *s)
2381{
2382 MpegTSContext *ts = s->priv_data;
2383 mpegts_free(ts);
2384 return 0;
2385}
2386
2387static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2388 int64_t *ppos, int64_t pos_limit)
2389{
2390 MpegTSContext *ts = s->priv_data;
2391 int64_t pos, timestamp;
2392 uint8_t buf[TS_PACKET_SIZE];
2393 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2394 int pos47 = ts->pos47_full % ts->raw_packet_size;
2395 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2396 while(pos < pos_limit) {
2397 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2398 return AV_NOPTS_VALUE;
2399 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2400 return AV_NOPTS_VALUE;
2401 if (buf[0] != 0x47) {
2402 avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2403 if (mpegts_resync(s) < 0)
2404 return AV_NOPTS_VALUE;
2405 pos = avio_tell(s->pb);
2406 continue;
2407 }
2408 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2409 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2410 *ppos = pos;
2411 return timestamp;
2412 }
2413 pos += ts->raw_packet_size;
2414 }
2415
2416 return AV_NOPTS_VALUE;
2417}
2418
2419static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2420 int64_t *ppos, int64_t pos_limit)
2421{
2422 MpegTSContext *ts = s->priv_data;
2423 int64_t pos;
2424 int pos47 = ts->pos47_full % ts->raw_packet_size;
2425 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2426 ff_read_frame_flush(s);
2427 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2428 return AV_NOPTS_VALUE;
2429 while(pos < pos_limit) {
2430 int ret;
2431 AVPacket pkt;
2432 av_init_packet(&pkt);
2433 ret= av_read_frame(s, &pkt);
2434 if(ret < 0)
2435 return AV_NOPTS_VALUE;
2436 av_free_packet(&pkt);
2437 if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0 && (pkt.flags & AV_PKT_FLAG_KEY)){
2438 ff_reduce_index(s, pkt.stream_index);
2439 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2440 if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
2441 *ppos= pkt.pos;
2442 return pkt.dts;
2443 }
2444 }
2445 pos = pkt.pos;
2446 }
2447
2448 return AV_NOPTS_VALUE;
2449}
2450
2451static int read_seek2(AVFormatContext *s,
2452 int stream_index,
2453 int64_t min_ts,
2454 int64_t target_ts,
2455 int64_t max_ts,
2456 int flags)
2457{
2458 int64_t pos;
2459
2460 int64_t ts_ret, ts_adj;
2461 int stream_index_gen_search;
2462 AVStream *st;
2463 AVParserState *backup;
2464
2465 backup = ff_store_parser_state(s);
2466
2467 // detect direction of seeking for search purposes
2468 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
2469 AVSEEK_FLAG_BACKWARD : 0;
2470
2471 if (flags & AVSEEK_FLAG_BYTE) {
2472 // use position directly, we will search starting from it
2473 pos = target_ts;
2474 } else {
2475 // search for some position with good timestamp match
2476 if (stream_index < 0) {
2477 stream_index_gen_search = av_find_default_stream_index(s);
2478 if (stream_index_gen_search < 0) {
2479 ff_restore_parser_state(s, backup);
2480 return -1;
2481 }
2482
2483 st = s->streams[stream_index_gen_search];
2484 // timestamp for default must be expressed in AV_TIME_BASE units
2485 ts_adj = av_rescale(target_ts,
2486 st->time_base.den,
2487 AV_TIME_BASE * (int64_t)st->time_base.num);
2488 } else {
2489 ts_adj = target_ts;
2490 stream_index_gen_search = stream_index;
2491 }
2492 pos = ff_gen_search(s, stream_index_gen_search, ts_adj,
2493 0, INT64_MAX, -1,
2494 AV_NOPTS_VALUE,
2495 AV_NOPTS_VALUE,
2496 flags, &ts_ret, mpegts_get_dts);
2497 if (pos < 0) {
2498 ff_restore_parser_state(s, backup);
2499 return -1;
2500 }
2501 }
2502
2503 // search for actual matching keyframe/starting position for all streams
2504 if (ff_gen_syncpoint_search(s, stream_index, pos,
2505 min_ts, target_ts, max_ts,
2506 flags) < 0) {
2507 ff_restore_parser_state(s, backup);
2508 return -1;
2509 }
2510
2511 ff_free_parser_state(s, backup);
2512 return 0;
2513}
2514
2515static int mpegts_read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
2516 int ret;
2517 if (flags & AVSEEK_FLAG_BACKWARD) {
2518 flags &= ~AVSEEK_FLAG_BACKWARD;
2519 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
2520 if (ret < 0) {
2521 // for compatibility reasons, seek to the best-fitting timestamp
2522 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
2523 }
2524 } else {
2525 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
2526 if (ret < 0)
2527 // for compatibility reasons, seek to the best-fitting timestamp
2528 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
2529 }
2530 return ret;
2531}
2532
2533
2534/**************************************************************/
2535/* parsing functions - called from other demuxers such as RTP */
2536
2537MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2538{
2539 MpegTSContext *ts;
2540
2541 ts = av_mallocz(sizeof(MpegTSContext));
2542 if (!ts)
2543 return NULL;
2544 /* no stream case, currently used by RTP */
2545 ts->raw_packet_size = TS_PACKET_SIZE;
2546 ts->stream = s;
2547 ts->auto_guess = 1;
2548 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2549 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2550
2551 return ts;
2552}
2553
2554/* return the consumed length if a packet was output, or -1 if no
2555 packet is output */
2556int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2557 const uint8_t *buf, int len)
2558{
2559 int len1;
2560
2561 len1 = len;
2562 ts->pkt = pkt;
2563 for(;;) {
2564 ts->stop_parse = 0;
2565 if (len < TS_PACKET_SIZE)
2566 return -1;
2567 if (buf[0] != 0x47) {
2568 buf++;
2569 len--;
2570 } else {
2571 handle_packet(ts, buf);
2572 buf += TS_PACKET_SIZE;
2573 len -= TS_PACKET_SIZE;
2574 if (ts->stop_parse == 1)
2575 break;
2576 }
2577 }
2578 return len1 - len;
2579}
2580
2581void ff_mpegts_parse_close(MpegTSContext *ts)
2582{
2583 mpegts_free(ts);
2584 av_free(ts);
2585}
2586
2587AVInputFormat ff_mpegts_demuxer = {
2588 .name = "mpegts",
2589 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2590 .priv_data_size = sizeof(MpegTSContext),
2591 .read_probe = mpegts_probe,
2592 .read_header = mpegts_read_header,
2593 .read_packet = mpegts_read_packet,
2594 .read_close = mpegts_read_close,
2595 .read_seek = mpegts_read_seek,
2596 .read_timestamp = mpegts_get_dts,
2597 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT | AVFMT_GENERIC_INDEX,
2598 .priv_class = &mpegts_class,
2599};
2600
2601AVInputFormat ff_mpegtsraw_demuxer = {
2602 .name = "mpegtsraw",
2603 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2604 .priv_data_size = sizeof(MpegTSContext),
2605 .read_header = mpegts_read_header,
2606 .read_packet = mpegts_raw_read_packet,
2607 .read_close = mpegts_read_close,
2608 .read_seek = mpegts_read_seek,
2609 .read_timestamp = mpegts_get_dts,
2610 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT | AVFMT_GENERIC_INDEX,
2611 .priv_class = &mpegtsraw_class,
2612};
2613