summaryrefslogtreecommitdiff
path: root/libavformat/mpegts.c (plain)
blob: 84d217c128b2cd94cbdd87e0ae4c7eb713565d6e
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 { MKTAG('D','T','S','H'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
644 { 0 },
645};
646
647static const StreamType METADATA_types[] = {
648 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
649 { 0 },
650};
651
652/* descriptor present */
653static const StreamType DESC_types[] = {
654 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
655 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
656 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
657 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
658 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
659 { 0 },
660};
661
662static void mpegts_find_stream_type(AVStream *st,
663 uint32_t stream_type, const StreamType *types)
664{
665 if (avcodec_is_open(st->codec)) {
666 av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
667 return;
668 }
669
670 for (; types->stream_type; types++) {
671 if (stream_type == types->stream_type) {
672 st->codec->codec_type = types->codec_type;
673 st->codec->codec_id = types->codec_id;
674 st->request_probe = 0;
675 return;
676 }
677 }
678}
679
680static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
681 uint32_t stream_type, uint32_t prog_reg_desc)
682{
683 int old_codec_type= st->codec->codec_type;
684 int old_codec_id = st->codec->codec_id;
685
686 if (avcodec_is_open(st->codec)) {
687 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
688 return 0;
689 }
690
691 avpriv_set_pts_info(st, 33, 1, 90000);
692 st->priv_data = pes;
693 st->codec->codec_type = AVMEDIA_TYPE_DATA;
694 st->codec->codec_id = AV_CODEC_ID_NONE;
695 st->need_parsing = AVSTREAM_PARSE_FULL;
696 pes->st = st;
697 pes->stream_type = stream_type;
698
699 av_log(pes->stream, AV_LOG_DEBUG,
700 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
701 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
702
703 st->codec->codec_tag = pes->stream_type;
704
705 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
706 if ((prog_reg_desc == AV_RL32("HDMV") ||
707 prog_reg_desc == AV_RL32("HDPR")) &&
708 st->codec->codec_id == AV_CODEC_ID_NONE) {
709 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
710 if (pes->stream_type == 0x83) {
711 // HDMV TrueHD streams also contain an AC3 coded version of the
712 // audio track - add a second stream for this
713 AVStream *sub_st;
714 // priv_data cannot be shared between streams
715 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
716 if (!sub_pes)
717 return AVERROR(ENOMEM);
718 memcpy(sub_pes, pes, sizeof(*sub_pes));
719
720 sub_st = avformat_new_stream(pes->stream, NULL);
721 if (!sub_st) {
722 av_free(sub_pes);
723 return AVERROR(ENOMEM);
724 }
725
726 sub_st->id = pes->pid;
727 avpriv_set_pts_info(sub_st, 33, 1, 90000);
728 sub_st->priv_data = sub_pes;
729 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
730 sub_st->codec->codec_id = AV_CODEC_ID_AC3;
731 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
732 sub_pes->sub_st = pes->sub_st = sub_st;
733 }
734 if (pes->stream_type == 0x81) {
735 // HDMV AC3 streams also contain an TRUEHD coded version of the
736 // audio track - add a second stream for this
737 AVStream *sub_st;
738 // priv_data cannot be shared between streams
739 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
740 if (!sub_pes)
741 return AVERROR(ENOMEM);
742 memcpy(sub_pes, pes, sizeof(*sub_pes));
743
744 sub_st = avformat_new_stream(pes->stream, NULL);
745 if (!sub_st) {
746 av_free(sub_pes);
747 return AVERROR(ENOMEM);
748 }
749
750 sub_st->id = pes->pid;
751 avpriv_set_pts_info(sub_st, 33, 1, 90000);
752 sub_st->priv_data = sub_pes;
753 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
754 sub_st->codec->codec_id = AV_CODEC_ID_TRUEHD;
755 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
756 sub_st->discard = AVDISCARD_ALL;
757 sub_pes->sub_st = pes->sub_st = sub_st;
758 }
759 }
760 if (st->codec->codec_id == AV_CODEC_ID_NONE && pes->stream_type == 0x82) {
761 AVStream *sub_st;
762 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
763 if (!sub_pes)
764 return AVERROR(ENOMEM);
765 memcpy(sub_pes, pes, sizeof(*sub_pes));
766 sub_st = avformat_new_stream(pes->stream, NULL);
767 if (!sub_st) {
768 av_free(sub_pes);
769 return AVERROR(ENOMEM);
770 }
771
772 sub_st->id = pes->pid;
773 av_set_pts_info(sub_st, 33, 1, 90000);
774 sub_st->priv_data = sub_pes;
775 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
776 sub_st->codec->codec_id = CODEC_ID_DTS;
777 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
778 sub_pes->sub_st = pes->sub_st = sub_st;
779 }
780
781 if (st->codec->codec_id == AV_CODEC_ID_NONE)
782 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
783 if (st->codec->codec_id == AV_CODEC_ID_NONE){
784 st->codec->codec_id = old_codec_id;
785 st->codec->codec_type= old_codec_type;
786 }
787
788 return 0;
789}
790
791static void new_pes_packet(PESContext *pes, AVPacket *pkt)
792{
793 av_init_packet(pkt);
794
795 pkt->buf = pes->buffer;
796 pkt->data = pes->buffer->data;
797 pkt->size = pes->data_index;
798
799 if(pes->total_size != MAX_PES_PAYLOAD &&
800 pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
801 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
802 pes->flags |= AV_PKT_FLAG_CORRUPT;
803 }
804 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
805
806 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
807 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
808 pkt->stream_index = pes->sub_st->index;
809 else if (pes->sub_st && pes->stream_type == 0x81 && pes->extended_stream_id == 0x72)
810 pkt->stream_index = pes->sub_st->index;
811 else
812 pkt->stream_index = pes->st->index;
813 pkt->pts = pes->pts;
814 pkt->dts = pes->dts;
815 /* store position of first TS packet of this PES packet */
816 pkt->pos = pes->ts_packet_pos;
817 pkt->flags = pes->flags;
818
819 /* reset pts values */
820 pes->pts = AV_NOPTS_VALUE;
821 pes->dts = AV_NOPTS_VALUE;
822 pes->buffer = NULL;
823 pes->data_index = 0;
824 pes->flags = 0;
825}
826
827static uint64_t get_ts64(GetBitContext *gb, int bits)
828{
829 if (get_bits_left(gb) < bits)
830 return AV_NOPTS_VALUE;
831 return get_bits64(gb, bits);
832}
833
834static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
835{
836 GetBitContext gb;
837 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
838 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
839 int dts_flag = -1, cts_flag = -1;
840 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
841
842 init_get_bits(&gb, buf, buf_size*8);
843
844 if (sl->use_au_start)
845 au_start_flag = get_bits1(&gb);
846 if (sl->use_au_end)
847 au_end_flag = get_bits1(&gb);
848 if (!sl->use_au_start && !sl->use_au_end)
849 au_start_flag = au_end_flag = 1;
850 if (sl->ocr_len > 0)
851 ocr_flag = get_bits1(&gb);
852 if (sl->use_idle)
853 idle_flag = get_bits1(&gb);
854 if (sl->use_padding)
855 padding_flag = get_bits1(&gb);
856 if (padding_flag)
857 padding_bits = get_bits(&gb, 3);
858
859 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
860 if (sl->packet_seq_num_len)
861 skip_bits_long(&gb, sl->packet_seq_num_len);
862 if (sl->degr_prior_len)
863 if (get_bits1(&gb))
864 skip_bits(&gb, sl->degr_prior_len);
865 if (ocr_flag)
866 skip_bits_long(&gb, sl->ocr_len);
867 if (au_start_flag) {
868 if (sl->use_rand_acc_pt)
869 get_bits1(&gb);
870 if (sl->au_seq_num_len > 0)
871 skip_bits_long(&gb, sl->au_seq_num_len);
872 if (sl->use_timestamps) {
873 dts_flag = get_bits1(&gb);
874 cts_flag = get_bits1(&gb);
875 }
876 }
877 if (sl->inst_bitrate_len)
878 inst_bitrate_flag = get_bits1(&gb);
879 if (dts_flag == 1)
880 dts = get_ts64(&gb, sl->timestamp_len);
881 if (cts_flag == 1)
882 cts = get_ts64(&gb, sl->timestamp_len);
883 if (sl->au_len > 0)
884 skip_bits_long(&gb, sl->au_len);
885 if (inst_bitrate_flag)
886 skip_bits_long(&gb, sl->inst_bitrate_len);
887 }
888
889 if (dts != AV_NOPTS_VALUE)
890 pes->dts = dts;
891 if (cts != AV_NOPTS_VALUE)
892 pes->pts = cts;
893
894 if (sl->timestamp_len && sl->timestamp_res)
895 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
896
897 return (get_bits_count(&gb) + 7) >> 3;
898}
899
900/* return non zero if a packet could be constructed */
901static int mpegts_push_data(MpegTSFilter *filter,
902 const uint8_t *buf, int buf_size, int is_start,
903 int64_t pos, int64_t pcr)
904{
905 PESContext *pes = filter->u.pes_filter.opaque;
906 MpegTSContext *ts = pes->ts;
907 const uint8_t *p;
908 int len, code;
909
910 if(!ts->pkt)
911 return 0;
912
913 if (pcr != -1)
914 pes->last_pcr = pcr;
915
916 if (is_start) {
917 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
918 new_pes_packet(pes, ts->pkt);
919 ts->stop_parse = 1;
920 }
921 pes->state = MPEGTS_HEADER;
922 pes->data_index = 0;
923 pes->ts_packet_pos = pos;
924 }
925 p = buf;
926 while (buf_size > 0) {
927 switch(pes->state) {
928 case MPEGTS_HEADER:
929 len = PES_START_SIZE - pes->data_index;
930 if (len > buf_size)
931 len = buf_size;
932 memcpy(pes->header + pes->data_index, p, len);
933 pes->data_index += len;
934 p += len;
935 buf_size -= len;
936 if (pes->data_index == PES_START_SIZE) {
937 /* we got all the PES or section header. We can now
938 decide */
939 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
940 pes->header[2] == 0x01) {
941 /* it must be an mpeg2 PES stream */
942 code = pes->header[3] | 0x100;
943 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
944
945 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
946 (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
947 code == 0x1be) /* padding_stream */
948 goto skip;
949
950 /* stream not present in PMT */
951 if (!pes->st) {
952 pes->st = avformat_new_stream(ts->stream, NULL);
953 if (!pes->st)
954 return AVERROR(ENOMEM);
955 pes->st->id = pes->pid;
956 mpegts_set_stream_info(pes->st, pes, 0, 0);
957 }
958
959 pes->total_size = AV_RB16(pes->header + 4);
960 /* NOTE: a zero total size means the PES size is
961 unbounded */
962 if (!pes->total_size)
963 pes->total_size = MAX_PES_PAYLOAD;
964
965 /* allocate pes buffer */
966 pes->buffer = av_buffer_alloc(pes->total_size +
967 FF_INPUT_BUFFER_PADDING_SIZE);
968 if (!pes->buffer)
969 return AVERROR(ENOMEM);
970
971 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
972 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
973 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
974 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
975 pes->state = MPEGTS_PESHEADER;
976 if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
977 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
978 pes->pid, pes->stream_type);
979 pes->st->request_probe= 1;
980 }
981 } else {
982 pes->state = MPEGTS_PAYLOAD;
983 pes->data_index = 0;
984 }
985 } else {
986 /* otherwise, it should be a table */
987 /* skip packet */
988 skip:
989 pes->state = MPEGTS_SKIP;
990 continue;
991 }
992 }
993 break;
994 /**********************************************/
995 /* PES packing parsing */
996 case MPEGTS_PESHEADER:
997 len = PES_HEADER_SIZE - pes->data_index;
998 if (len < 0)
999 return -1;
1000 if (len > buf_size)
1001 len = buf_size;
1002 memcpy(pes->header + pes->data_index, p, len);
1003 pes->data_index += len;
1004 p += len;
1005 buf_size -= len;
1006 if (pes->data_index == PES_HEADER_SIZE) {
1007 pes->pes_header_size = pes->header[8] + 9;
1008 pes->state = MPEGTS_PESHEADER_FILL;
1009 }
1010 break;
1011 case MPEGTS_PESHEADER_FILL:
1012 len = pes->pes_header_size - pes->data_index;
1013 if (len < 0)
1014 return -1;
1015 if (len > buf_size)
1016 len = buf_size;
1017 memcpy(pes->header + pes->data_index, p, len);
1018 pes->data_index += len;
1019 p += len;
1020 buf_size -= len;
1021 if (pes->data_index == pes->pes_header_size) {
1022 const uint8_t *r;
1023 unsigned int flags, pes_ext, skip;
1024
1025 flags = pes->header[7];
1026 r = pes->header + 9;
1027 pes->pts = AV_NOPTS_VALUE;
1028 pes->dts = AV_NOPTS_VALUE;
1029 if ((flags & 0xc0) == 0x80) {
1030 pes->dts = pes->pts = ff_parse_pes_pts(r);
1031 r += 5;
1032 } else if ((flags & 0xc0) == 0xc0) {
1033 pes->pts = ff_parse_pes_pts(r);
1034 r += 5;
1035 pes->dts = ff_parse_pes_pts(r);
1036 r += 5;
1037 }
1038 pes->extended_stream_id = -1;
1039 if (flags & 0x01) { /* PES extension */
1040 pes_ext = *r++;
1041 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1042 skip = (pes_ext >> 4) & 0xb;
1043 skip += skip & 0x9;
1044 r += skip;
1045 if ((pes_ext & 0x41) == 0x01 &&
1046 (r + 2) <= (pes->header + pes->pes_header_size)) {
1047 /* PES extension 2 */
1048 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1049 pes->extended_stream_id = r[1];
1050 }
1051 }
1052
1053 /* we got the full header. We parse it and get the payload */
1054 pes->state = MPEGTS_PAYLOAD;
1055 pes->data_index = 0;
1056 if (pes->stream_type == 0x12 && buf_size > 0) {
1057 int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
1058 pes->pes_header_size += sl_header_bytes;
1059 p += sl_header_bytes;
1060 buf_size -= sl_header_bytes;
1061 }
1062 if (pes->stream_type == 0x15 && buf_size >= 5) {
1063 /* skip metadata access unit header */
1064 pes->pes_header_size += 5;
1065 p += 5;
1066 buf_size -= 5;
1067 }
1068 if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1069 AVProgram *p = NULL;
1070 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1071 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1072 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1073 if (f && f->type == MPEGTS_PES) {
1074 PESContext *pcrpes = f->u.pes_filter.opaque;
1075 if (pcrpes && pcrpes->last_pcr != -1 && pcrpes->st && pcrpes->st->discard != AVDISCARD_ALL) {
1076 // teletext packets do not always have correct timestamps,
1077 // the standard says they should be handled after 40.6 ms at most,
1078 // and the pcr error to this packet should be no more than 100 ms.
1079 // TODO: we should interpolate the PCR, not just use the last one
1080 int64_t pcr = pcrpes->last_pcr / 300;
1081 pes->st->pts_wrap_reference = pcrpes->st->pts_wrap_reference;
1082 pes->st->pts_wrap_behavior = pcrpes->st->pts_wrap_behavior;
1083 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1084 pes->pts = pes->dts = pcr;
1085 } else if (pes->dts > pcr + 3654 + 9000) {
1086 pes->pts = pes->dts = pcr + 3654 + 9000;
1087 }
1088 break;
1089 }
1090 }
1091 }
1092 }
1093 }
1094 }
1095 break;
1096 case MPEGTS_PAYLOAD:
1097 if (buf_size > 0 && pes->buffer) {
1098 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
1099 new_pes_packet(pes, ts->pkt);
1100 pes->total_size = MAX_PES_PAYLOAD;
1101 pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
1102 if (!pes->buffer)
1103 return AVERROR(ENOMEM);
1104 ts->stop_parse = 1;
1105 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
1106 // pes packet size is < ts size packet and pes data is padded with 0xff
1107 // not sure if this is legal in ts but see issue #2392
1108 buf_size = pes->total_size;
1109 }
1110 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1111 pes->data_index += buf_size;
1112 }
1113 buf_size = 0;
1114 /* emit complete packets with known packet size
1115 * decreases demuxer delay for infrequent packets like subtitles from
1116 * a couple of seconds to milliseconds for properly muxed files.
1117 * total_size is the number of bytes following pes_packet_length
1118 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1119 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1120 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1121 ts->stop_parse = 1;
1122 new_pes_packet(pes, ts->pkt);
1123 }
1124 break;
1125 case MPEGTS_SKIP:
1126 buf_size = 0;
1127 break;
1128 }
1129 }
1130
1131 return 0;
1132}
1133
1134static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1135{
1136 MpegTSFilter *tss;
1137 PESContext *pes;
1138
1139 /* if no pid found, then add a pid context */
1140 pes = av_mallocz(sizeof(PESContext));
1141 if (!pes)
1142 return 0;
1143 pes->ts = ts;
1144 pes->stream = ts->stream;
1145 pes->pid = pid;
1146 pes->pcr_pid = pcr_pid;
1147 pes->state = MPEGTS_SKIP;
1148 pes->pts = AV_NOPTS_VALUE;
1149 pes->dts = AV_NOPTS_VALUE;
1150 pes->last_pcr = -1;
1151 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1152 if (!tss) {
1153 av_free(pes);
1154 return 0;
1155 }
1156 return pes;
1157}
1158
1159#define MAX_LEVEL 4
1160typedef struct {
1161 AVFormatContext *s;
1162 AVIOContext pb;
1163 Mp4Descr *descr;
1164 Mp4Descr *active_descr;
1165 int descr_count;
1166 int max_descr_count;
1167 int level;
1168} MP4DescrParseContext;
1169
1170static int init_MP4DescrParseContext(
1171 MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1172 unsigned size, Mp4Descr *descr, int max_descr_count)
1173{
1174 int ret;
1175 if (size > (1<<30))
1176 return AVERROR_INVALIDDATA;
1177
1178 if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1179 NULL, NULL, NULL, NULL)) < 0)
1180 return ret;
1181
1182 d->s = s;
1183 d->level = 0;
1184 d->descr_count = 0;
1185 d->descr = descr;
1186 d->active_descr = NULL;
1187 d->max_descr_count = max_descr_count;
1188
1189 return 0;
1190}
1191
1192static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1193 int64_t new_off = avio_tell(pb);
1194 (*len) -= new_off - *off;
1195 *off = new_off;
1196}
1197
1198static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1199 int target_tag);
1200
1201static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1202{
1203 while (len > 0) {
1204 if (parse_mp4_descr(d, off, len, 0) < 0)
1205 return -1;
1206 update_offsets(&d->pb, &off, &len);
1207 }
1208 return 0;
1209}
1210
1211static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1212{
1213 avio_rb16(&d->pb); // ID
1214 avio_r8(&d->pb);
1215 avio_r8(&d->pb);
1216 avio_r8(&d->pb);
1217 avio_r8(&d->pb);
1218 avio_r8(&d->pb);
1219 update_offsets(&d->pb, &off, &len);
1220 return parse_mp4_descr_arr(d, off, len);
1221}
1222
1223static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1224{
1225 int id_flags;
1226 if (len < 2)
1227 return 0;
1228 id_flags = avio_rb16(&d->pb);
1229 if (!(id_flags & 0x0020)) { //URL_Flag
1230 update_offsets(&d->pb, &off, &len);
1231 return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1232 } else {
1233 return 0;
1234 }
1235}
1236
1237static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1238{
1239 int es_id = 0;
1240 if (d->descr_count >= d->max_descr_count)
1241 return -1;
1242 ff_mp4_parse_es_descr(&d->pb, &es_id);
1243 d->active_descr = d->descr + (d->descr_count++);
1244
1245 d->active_descr->es_id = es_id;
1246 update_offsets(&d->pb, &off, &len);
1247 parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1248 update_offsets(&d->pb, &off, &len);
1249 if (len > 0)
1250 parse_mp4_descr(d, off, len, MP4SLDescrTag);
1251 d->active_descr = NULL;
1252 return 0;
1253}
1254
1255static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1256{
1257 Mp4Descr *descr = d->active_descr;
1258 if (!descr)
1259 return -1;
1260 d->active_descr->dec_config_descr = av_malloc(len);
1261 if (!descr->dec_config_descr)
1262 return AVERROR(ENOMEM);
1263 descr->dec_config_descr_len = len;
1264 avio_read(&d->pb, descr->dec_config_descr, len);
1265 return 0;
1266}
1267
1268static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1269{
1270 Mp4Descr *descr = d->active_descr;
1271 int predefined;
1272 if (!descr)
1273 return -1;
1274
1275 predefined = avio_r8(&d->pb);
1276 if (!predefined) {
1277 int lengths;
1278 int flags = avio_r8(&d->pb);
1279 descr->sl.use_au_start = !!(flags & 0x80);
1280 descr->sl.use_au_end = !!(flags & 0x40);
1281 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1282 descr->sl.use_padding = !!(flags & 0x08);
1283 descr->sl.use_timestamps = !!(flags & 0x04);
1284 descr->sl.use_idle = !!(flags & 0x02);
1285 descr->sl.timestamp_res = avio_rb32(&d->pb);
1286 avio_rb32(&d->pb);
1287 descr->sl.timestamp_len = avio_r8(&d->pb);
1288 descr->sl.ocr_len = avio_r8(&d->pb);
1289 descr->sl.au_len = avio_r8(&d->pb);
1290 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1291 lengths = avio_rb16(&d->pb);
1292 descr->sl.degr_prior_len = lengths >> 12;
1293 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1294 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1295 } else {
1296 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1297 }
1298 return 0;
1299}
1300
1301static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1302 int target_tag) {
1303 int tag;
1304 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1305 update_offsets(&d->pb, &off, &len);
1306 if (len < 0 || len1 > len || len1 <= 0) {
1307 av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1308 return -1;
1309 }
1310
1311 if (d->level++ >= MAX_LEVEL) {
1312 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1313 goto done;
1314 }
1315
1316 if (target_tag && tag != target_tag) {
1317 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1318 goto done;
1319 }
1320
1321 switch (tag) {
1322 case MP4IODescrTag:
1323 parse_MP4IODescrTag(d, off, len1);
1324 break;
1325 case MP4ODescrTag:
1326 parse_MP4ODescrTag(d, off, len1);
1327 break;
1328 case MP4ESDescrTag:
1329 parse_MP4ESDescrTag(d, off, len1);
1330 break;
1331 case MP4DecConfigDescrTag:
1332 parse_MP4DecConfigDescrTag(d, off, len1);
1333 break;
1334 case MP4SLDescrTag:
1335 parse_MP4SLDescrTag(d, off, len1);
1336 break;
1337 }
1338
1339done:
1340 d->level--;
1341 avio_seek(&d->pb, off + len1, SEEK_SET);
1342 return 0;
1343}
1344
1345static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1346 Mp4Descr *descr, int *descr_count, int max_descr_count)
1347{
1348 MP4DescrParseContext d;
1349 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1350 return -1;
1351
1352 parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1353
1354 *descr_count = d.descr_count;
1355 return 0;
1356}
1357
1358static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1359 Mp4Descr *descr, int *descr_count, int max_descr_count)
1360{
1361 MP4DescrParseContext d;
1362 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1363 return -1;
1364
1365 parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1366
1367 *descr_count = d.descr_count;
1368 return 0;
1369}
1370
1371static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1372{
1373 MpegTSContext *ts = filter->u.section_filter.opaque;
1374 SectionHeader h;
1375 const uint8_t *p, *p_end;
1376 AVIOContext pb;
1377 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1378 int mp4_descr_count = 0;
1379 int i, pid;
1380 AVFormatContext *s = ts->stream;
1381
1382 p_end = section + section_len - 4;
1383 p = section;
1384 if (parse_section_header(&h, &p, p_end) < 0)
1385 return;
1386 if (h.tid != M4OD_TID)
1387 return;
1388
1389 mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1390
1391 for (pid = 0; pid < NB_PID_MAX; pid++) {
1392 if (!ts->pids[pid])
1393 continue;
1394 for (i = 0; i < mp4_descr_count; i++) {
1395 PESContext *pes;
1396 AVStream *st;
1397 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1398 continue;
1399 if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1400 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1401 continue;
1402 }
1403 pes = ts->pids[pid]->u.pes_filter.opaque;
1404 st = pes->st;
1405 if (!st) {
1406 continue;
1407 }
1408
1409 pes->sl = mp4_descr[i].sl;
1410
1411 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1412 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1413 ff_mp4_read_dec_config_descr(s, st, &pb);
1414 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1415 st->codec->extradata_size > 0)
1416 st->need_parsing = 0;
1417 if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1418 st->codec->extradata_size > 0)
1419 st->need_parsing = 0;
1420
1421 if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1422 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1423 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1424 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1425 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1426 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1427 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1428 }
1429 }
1430 }
1431 for (i = 0; i < mp4_descr_count; i++)
1432 av_free(mp4_descr[i].dec_config_descr);
1433}
1434
1435int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1436 const uint8_t **pp, const uint8_t *desc_list_end,
1437 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1438 MpegTSContext *ts)
1439{
1440 const uint8_t *desc_end;
1441 int desc_len, desc_tag, desc_es_id;
1442 char language[252];
1443 int i;
1444
1445 desc_tag = get8(pp, desc_list_end);
1446 if (desc_tag < 0)
1447 return -1;
1448 desc_len = get8(pp, desc_list_end);
1449 if (desc_len < 0)
1450 return -1;
1451 desc_end = *pp + desc_len;
1452 if (desc_end > desc_list_end)
1453 return -1;
1454
1455 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1456
1457 if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1458 stream_type == STREAM_TYPE_PRIVATE_DATA)
1459 mpegts_find_stream_type(st, desc_tag, DESC_types);
1460
1461 switch(desc_tag) {
1462 case 0x1E: /* SL descriptor */
1463 desc_es_id = get16(pp, desc_end);
1464 if (ts && ts->pids[pid])
1465 ts->pids[pid]->es_id = desc_es_id;
1466 for (i = 0; i < mp4_descr_count; i++)
1467 if (mp4_descr[i].dec_config_descr_len &&
1468 mp4_descr[i].es_id == desc_es_id) {
1469 AVIOContext pb;
1470 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1471 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1472 ff_mp4_read_dec_config_descr(fc, st, &pb);
1473 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1474 st->codec->extradata_size > 0)
1475 st->need_parsing = 0;
1476 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1477 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1478 }
1479 break;
1480 case 0x1F: /* FMC descriptor */
1481 get16(pp, desc_end);
1482 if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1483 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1484 AVIOContext pb;
1485 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1486 mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1487 ff_mp4_read_dec_config_descr(fc, st, &pb);
1488 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1489 st->codec->extradata_size > 0){
1490 st->request_probe= st->need_parsing = 0;
1491 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
1492 }
1493 }
1494 break;
1495 case 0x56: /* DVB teletext descriptor */
1496 language[0] = get8(pp, desc_end);
1497 language[1] = get8(pp, desc_end);
1498 language[2] = get8(pp, desc_end);
1499 language[3] = 0;
1500 av_dict_set(&st->metadata, "language", language, 0);
1501 break;
1502 case 0x59: /* subtitling descriptor */
1503 language[0] = get8(pp, desc_end);
1504 language[1] = get8(pp, desc_end);
1505 language[2] = get8(pp, desc_end);
1506 language[3] = 0;
1507 /* hearing impaired subtitles detection */
1508 switch(get8(pp, desc_end)) {
1509 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1510 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1511 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1512 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1513 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1514 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1515 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1516 break;
1517 }
1518 if (st->codec->extradata) {
1519 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1520 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1521 } else {
1522 if (!ff_alloc_extradata(st->codec, 4)) {
1523 memcpy(st->codec->extradata, *pp, 4);
1524 }
1525 }
1526 *pp += 4;
1527 av_dict_set(&st->metadata, "language", language, 0);
1528 break;
1529 case 0x0a: /* ISO 639 language descriptor */
1530 for (i = 0; i + 4 <= desc_len; i += 4) {
1531 language[i + 0] = get8(pp, desc_end);
1532 language[i + 1] = get8(pp, desc_end);
1533 language[i + 2] = get8(pp, desc_end);
1534 language[i + 3] = ',';
1535 switch (get8(pp, desc_end)) {
1536 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1537 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1538 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1539 }
1540 }
1541 if (i) {
1542 language[i - 1] = 0;
1543 av_dict_set(&st->metadata, "language", language, 0);
1544 }
1545 break;
1546 case 0x05: /* registration descriptor */
1547 st->codec->codec_tag = bytestream_get_le32(pp);
1548 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1549 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1550 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1551 break;
1552 case 0x52: /* stream identifier descriptor */
1553 st->stream_identifier = 1 + get8(pp, desc_end);
1554 break;
1555 case 0x26: /* metadata descriptor */
1556 if (get16(pp, desc_end) == 0xFFFF)
1557 *pp += 4;
1558 if (get8(pp, desc_end) == 0xFF) {
1559 st->codec->codec_tag = bytestream_get_le32(pp);
1560 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1561 mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
1562 }
1563 break;
1564 default:
1565 break;
1566 }
1567 *pp = desc_end;
1568 return 0;
1569}
1570
1571static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1572{
1573 MpegTSContext *ts = filter->u.section_filter.opaque;
1574 SectionHeader h1, *h = &h1;
1575 PESContext *pes;
1576 AVStream *st;
1577 const uint8_t *p, *p_end, *desc_list_end;
1578 int program_info_length, pcr_pid, pid, stream_type;
1579 int desc_list_len;
1580 uint32_t prog_reg_desc = 0; /* registration descriptor */
1581
1582 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1583 int mp4_descr_count = 0;
1584 int i;
1585
1586 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1587 hex_dump_debug(ts->stream, section, section_len);
1588
1589 p_end = section + section_len - 4;
1590 p = section;
1591 if (parse_section_header(h, &p, p_end) < 0)
1592 return;
1593
1594 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1595 h->id, h->sec_num, h->last_sec_num);
1596
1597 if (h->tid != PMT_TID)
1598 return;
1599
1600 clear_program(ts, h->id);
1601 pcr_pid = get16(&p, p_end);
1602 if (pcr_pid < 0)
1603 return;
1604 pcr_pid &= 0x1fff;
1605 add_pid_to_pmt(ts, h->id, pcr_pid);
1606 set_pcr_pid(ts->stream, h->id, pcr_pid);
1607
1608 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1609
1610 program_info_length = get16(&p, p_end);
1611 if (program_info_length < 0)
1612 return;
1613 program_info_length &= 0xfff;
1614 while(program_info_length >= 2) {
1615 uint8_t tag, len;
1616 tag = get8(&p, p_end);
1617 len = get8(&p, p_end);
1618
1619 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1620
1621 if(len > program_info_length - 2)
1622 //something else is broken, exit the program_descriptors_loop
1623 break;
1624 program_info_length -= len + 2;
1625 if (tag == 0x1d) { // IOD descriptor
1626 get8(&p, p_end); // scope
1627 get8(&p, p_end); // label
1628 len -= 2;
1629 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1630 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1631 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1632 prog_reg_desc = bytestream_get_le32(&p);
1633 len -= 4;
1634 }
1635 p += len;
1636 }
1637 p += program_info_length;
1638 if (p >= p_end)
1639 goto out;
1640
1641 // stop parsing after pmt, we found header
1642 if (!ts->stream->nb_streams)
1643 ts->stop_parse = 2;
1644
1645 for(;;) {
1646 st = 0;
1647 pes = NULL;
1648 stream_type = get8(&p, p_end);
1649 if (stream_type < 0)
1650 break;
1651 pid = get16(&p, p_end);
1652 if (pid < 0)
1653 break;
1654 pid &= 0x1fff;
1655 if (pid == ts->current_pid)
1656 break;
1657
1658 /* now create stream */
1659 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1660 pes = ts->pids[pid]->u.pes_filter.opaque;
1661 if (!pes->st) {
1662 pes->st = avformat_new_stream(pes->stream, NULL);
1663 if (!pes->st)
1664 goto out;
1665 pes->st->id = pes->pid;
1666 }
1667 st = pes->st;
1668 } else if (stream_type != 0x13) {
1669 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1670 pes = add_pes_stream(ts, pid, pcr_pid);
1671 if (pes) {
1672 st = avformat_new_stream(pes->stream, NULL);
1673 if (!st)
1674 goto out;
1675 st->id = pes->pid;
1676 }
1677 } else {
1678 int idx = ff_find_stream_index(ts->stream, pid);
1679 if (idx >= 0) {
1680 st = ts->stream->streams[idx];
1681 } else {
1682 st = avformat_new_stream(ts->stream, NULL);
1683 if (!st)
1684 goto out;
1685 st->id = pid;
1686 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1687 }
1688 }
1689
1690 if (!st)
1691 goto out;
1692
1693 if (pes && !pes->stream_type)
1694 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1695
1696 add_pid_to_pmt(ts, h->id, pid);
1697
1698 ff_program_add_stream_index(ts->stream, h->id, st->index);
1699
1700 desc_list_len = get16(&p, p_end);
1701 if (desc_list_len < 0)
1702 break;
1703 desc_list_len &= 0xfff;
1704 desc_list_end = p + desc_list_len;
1705 if (desc_list_end > p_end)
1706 break;
1707 for(;;) {
1708 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1709 mp4_descr, mp4_descr_count, pid, ts) < 0)
1710 break;
1711
1712 if (pes && prog_reg_desc == AV_RL32("HDMV") && (stream_type == 0x83 || stream_type == 0x81) && pes->sub_st) {
1713 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1714 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1715 }
1716 }
1717 p = desc_list_end;
1718 }
1719
1720 out:
1721 for (i = 0; i < mp4_descr_count; i++)
1722 av_free(mp4_descr[i].dec_config_descr);
1723}
1724
1725static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1726{
1727 MpegTSContext *ts = filter->u.section_filter.opaque;
1728 SectionHeader h1, *h = &h1;
1729 const uint8_t *p, *p_end;
1730 int sid, pmt_pid;
1731 AVProgram *program;
1732
1733 av_dlog(ts->stream, "PAT:\n");
1734 hex_dump_debug(ts->stream, section, section_len);
1735
1736 p_end = section + section_len - 4;
1737 p = section;
1738 if (parse_section_header(h, &p, p_end) < 0)
1739 return;
1740 if (h->tid != PAT_TID)
1741 return;
1742
1743 ts->stream->ts_id = h->id;
1744
1745 clear_programs(ts);
1746 for(;;) {
1747 sid = get16(&p, p_end);
1748 if (sid < 0)
1749 break;
1750 pmt_pid = get16(&p, p_end);
1751 if (pmt_pid < 0)
1752 break;
1753 pmt_pid &= 0x1fff;
1754
1755 if (pmt_pid == ts->current_pid)
1756 break;
1757
1758 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1759
1760 if (sid == 0x0000) {
1761 /* NIT info */
1762 } else {
1763 MpegTSFilter *fil = ts->pids[pmt_pid];
1764 program = av_new_program(ts->stream, sid);
1765 program->program_num = sid;
1766 program->pmt_pid = pmt_pid;
1767 if (fil)
1768 if ( fil->type != MPEGTS_SECTION
1769 || fil->pid != pmt_pid
1770 || fil->u.section_filter.section_cb != pmt_cb)
1771 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1772
1773 if (!ts->pids[pmt_pid])
1774 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1775 add_pat_entry(ts, sid);
1776 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1777 add_pid_to_pmt(ts, sid, pmt_pid);
1778 }
1779 }
1780
1781 if (sid < 0) {
1782 int i,j;
1783 for (j=0; j<ts->stream->nb_programs; j++) {
1784 for (i=0; i<ts->nb_prg; i++)
1785 if (ts->prg[i].id == ts->stream->programs[j]->id)
1786 break;
1787 if (i==ts->nb_prg)
1788 clear_avprogram(ts, ts->stream->programs[j]->id);
1789 }
1790 }
1791}
1792
1793static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1794{
1795 MpegTSContext *ts = filter->u.section_filter.opaque;
1796 SectionHeader h1, *h = &h1;
1797 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1798 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1799 char *name, *provider_name;
1800
1801 av_dlog(ts->stream, "SDT:\n");
1802 hex_dump_debug(ts->stream, section, section_len);
1803
1804 p_end = section + section_len - 4;
1805 p = section;
1806 if (parse_section_header(h, &p, p_end) < 0)
1807 return;
1808 if (h->tid != SDT_TID)
1809 return;
1810 onid = get16(&p, p_end);
1811 if (onid < 0)
1812 return;
1813 val = get8(&p, p_end);
1814 if (val < 0)
1815 return;
1816 for(;;) {
1817 sid = get16(&p, p_end);
1818 if (sid < 0)
1819 break;
1820 val = get8(&p, p_end);
1821 if (val < 0)
1822 break;
1823 desc_list_len = get16(&p, p_end);
1824 if (desc_list_len < 0)
1825 break;
1826 desc_list_len &= 0xfff;
1827 desc_list_end = p + desc_list_len;
1828 if (desc_list_end > p_end)
1829 break;
1830 for(;;) {
1831 desc_tag = get8(&p, desc_list_end);
1832 if (desc_tag < 0)
1833 break;
1834 desc_len = get8(&p, desc_list_end);
1835 desc_end = p + desc_len;
1836 if (desc_end > desc_list_end)
1837 break;
1838
1839 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1840 desc_tag, desc_len);
1841
1842 switch(desc_tag) {
1843 case 0x48:
1844 service_type = get8(&p, p_end);
1845 if (service_type < 0)
1846 break;
1847 provider_name = getstr8(&p, p_end);
1848 if (!provider_name)
1849 break;
1850 name = getstr8(&p, p_end);
1851 if (name) {
1852 AVProgram *program = av_new_program(ts->stream, sid);
1853 if(program) {
1854 av_dict_set(&program->metadata, "service_name", name, 0);
1855 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1856 }
1857 }
1858 av_free(name);
1859 av_free(provider_name);
1860 break;
1861 default:
1862 break;
1863 }
1864 p = desc_end;
1865 }
1866 p = desc_list_end;
1867 }
1868}
1869
1870static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1871 const uint8_t *packet);
1872
1873/* handle one TS packet */
1874static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1875{
1876 AVFormatContext *s = ts->stream;
1877 MpegTSFilter *tss;
1878 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1879 has_adaptation, has_payload;
1880 const uint8_t *p, *p_end;
1881 int64_t pos;
1882
1883 pid = AV_RB16(packet + 1) & 0x1fff;
1884 if(pid && discard_pid(ts, pid))
1885 return 0;
1886 is_start = packet[1] & 0x40;
1887 tss = ts->pids[pid];
1888 if (ts->auto_guess && tss == NULL && is_start) {
1889 add_pes_stream(ts, pid, -1);
1890 tss = ts->pids[pid];
1891 }
1892 if (!tss)
1893 return 0;
1894 ts->current_pid = pid;
1895
1896 afc = (packet[3] >> 4) & 3;
1897 if (afc == 0) /* reserved value */
1898 return 0;
1899 has_adaptation = afc & 2;
1900 has_payload = afc & 1;
1901 is_discontinuity = has_adaptation
1902 && packet[4] != 0 /* with length > 0 */
1903 && (packet[5] & 0x80); /* and discontinuity indicated */
1904
1905 /* continuity check (currently not used) */
1906 cc = (packet[3] & 0xf);
1907 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1908 cc_ok = pid == 0x1FFF // null packet PID
1909 || is_discontinuity
1910 || tss->last_cc < 0
1911 || expected_cc == cc;
1912
1913 tss->last_cc = cc;
1914 if (!cc_ok) {
1915 av_log(ts->stream, AV_LOG_DEBUG,
1916 "Continuity check failed for pid %d expected %d got %d\n",
1917 pid, expected_cc, cc);
1918 if(tss->type == MPEGTS_PES) {
1919 PESContext *pc = tss->u.pes_filter.opaque;
1920 pc->flags |= AV_PKT_FLAG_CORRUPT;
1921 }
1922 }
1923
1924 if (!has_payload)
1925 return 0;
1926 p = packet + 4;
1927 if (has_adaptation) {
1928 /* skip adaptation field */
1929 p += p[0] + 1;
1930 }
1931 /* if past the end of packet, ignore */
1932 p_end = packet + TS_PACKET_SIZE;
1933 if (p >= p_end)
1934 return 0;
1935
1936 pos = avio_tell(ts->stream->pb);
1937 if (pos >= 0) {
1938 av_assert0(pos >= TS_PACKET_SIZE);
1939 ts->pos47_full = pos - TS_PACKET_SIZE;
1940 }
1941
1942 if (tss->type == MPEGTS_SECTION) {
1943 if (is_start) {
1944 /* pointer field present */
1945 len = *p++;
1946 if (p + len > p_end)
1947 return 0;
1948 if (len && cc_ok) {
1949 /* write remaining section bytes */
1950 write_section_data(s, tss,
1951 p, len, 0);
1952 /* check whether filter has been closed */
1953 if (!ts->pids[pid])
1954 return 0;
1955 }
1956 p += len;
1957 if (p < p_end) {
1958 write_section_data(s, tss,
1959 p, p_end - p, 1);
1960 }
1961 } else {
1962 if (cc_ok) {
1963 write_section_data(s, tss,
1964 p, p_end - p, 0);
1965 }
1966 }
1967 } else {
1968 int ret;
1969 int64_t pcr = -1;
1970 int64_t pcr_h;
1971 int pcr_l;
1972 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
1973 pcr = pcr_h * 300 + pcr_l;
1974 // Note: The position here points actually behind the current packet.
1975 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1976 pos - ts->raw_packet_size, pcr)) < 0)
1977 return ret;
1978 }
1979
1980 return 0;
1981}
1982
1983static void reanalyze(MpegTSContext *ts) {
1984 AVIOContext *pb = ts->stream->pb;
1985 int64_t pos = avio_tell(pb);
1986 if(pos < 0)
1987 return;
1988 pos -= ts->pos47_full;
1989 if (pos == TS_PACKET_SIZE) {
1990 ts->size_stat[0] ++;
1991 } else if (pos == TS_DVHS_PACKET_SIZE) {
1992 ts->size_stat[1] ++;
1993 } else if (pos == TS_FEC_PACKET_SIZE) {
1994 ts->size_stat[2] ++;
1995 }
1996
1997 ts->size_stat_count ++;
1998 if(ts->size_stat_count > SIZE_STAT_THRESHOLD) {
1999 int newsize = 0;
2000 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2001 newsize = TS_PACKET_SIZE;
2002 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2003 newsize = TS_DVHS_PACKET_SIZE;
2004 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2005 newsize = TS_FEC_PACKET_SIZE;
2006 }
2007 if (newsize && newsize != ts->raw_packet_size) {
2008 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2009 ts->raw_packet_size = newsize;
2010 }
2011 ts->size_stat_count = 0;
2012 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2013 }
2014}
2015
2016/* XXX: try to find a better synchro over several packets (use
2017 get_packet_size() ?) */
2018static int mpegts_resync(AVFormatContext *s)
2019{
2020 AVIOContext *pb = s->pb;
2021 int c, i;
2022
2023 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
2024 c = avio_r8(pb);
2025 if (url_feof(pb))
2026 return -1;
2027 if (c == 0x47) {
2028 avio_seek(pb, -1, SEEK_CUR);
2029 reanalyze(s->priv_data);
2030 return 0;
2031 }
2032 }
2033 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
2034 /* no sync found */
2035 return -1;
2036}
2037
2038/* return -1 if error or EOF. Return 0 if OK. */
2039static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
2040{
2041 AVIOContext *pb = s->pb;
2042 int len;
2043
2044 for(;;) {
2045 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2046 if (len != TS_PACKET_SIZE)
2047 return len < 0 ? len : AVERROR_EOF;
2048 /* check packet sync byte */
2049 if ((*data)[0] != 0x47) {
2050 /* find a new packet start */
2051 avio_seek(pb, -raw_packet_size, SEEK_CUR);
2052 if (mpegts_resync(s) < 0)
2053 return AVERROR(EAGAIN);
2054 else
2055 continue;
2056 } else {
2057 break;
2058 }
2059 }
2060 return 0;
2061}
2062
2063static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2064{
2065 AVIOContext *pb = s->pb;
2066 int skip = raw_packet_size - TS_PACKET_SIZE;
2067 if (skip > 0)
2068 avio_skip(pb, skip);
2069}
2070
2071static int handle_packets(MpegTSContext *ts, int nb_packets)
2072{
2073 AVFormatContext *s = ts->stream;
2074 uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
2075 const uint8_t *data;
2076 int packet_num, ret = 0;
2077
2078 if (avio_tell(s->pb) != ts->last_pos) {
2079 int i;
2080 av_dlog(ts->stream, "Skipping after seek\n");
2081 /* seek detected, flush pes buffer */
2082 for (i = 0; i < NB_PID_MAX; i++) {
2083 if (ts->pids[i]) {
2084 if (ts->pids[i]->type == MPEGTS_PES) {
2085 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2086 av_buffer_unref(&pes->buffer);
2087 pes->data_index = 0;
2088 pes->state = MPEGTS_SKIP; /* skip until pes header */
2089 pes->last_pcr = -1;
2090 }
2091 ts->pids[i]->last_cc = -1;
2092 }
2093 }
2094 }
2095
2096 ts->stop_parse = 0;
2097 packet_num = 0;
2098 memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2099 for(;;) {
2100 packet_num++;
2101 if (nb_packets != 0 && packet_num >= nb_packets ||
2102 ts->stop_parse > 1) {
2103 ret = AVERROR(EAGAIN);
2104 break;
2105 }
2106 if (ts->stop_parse > 0)
2107 break;
2108
2109 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2110 if (ret != 0)
2111 break;
2112 ret = handle_packet(ts, data);
2113 finished_reading_packet(s, ts->raw_packet_size);
2114 if (ret != 0)
2115 break;
2116 }
2117 ts->last_pos = avio_tell(s->pb);
2118 return ret;
2119}
2120
2121static int mpegts_probe(AVProbeData *p)
2122{
2123 const int size= p->buf_size;
2124 int maxscore=0;
2125 int sumscore=0;
2126 int i;
2127 int check_count= size / TS_FEC_PACKET_SIZE;
2128#define CHECK_COUNT 10
2129#define CHECK_BLOCK 100
2130
2131 if (check_count < CHECK_COUNT)
2132 return -1;
2133
2134 for (i=0; i<check_count; i+=CHECK_BLOCK){
2135 int left = FFMIN(check_count - i, CHECK_BLOCK);
2136 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
2137 int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
2138 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
2139 score = FFMAX3(score, dvhs_score, fec_score);
2140 sumscore += score;
2141 maxscore = FFMAX(maxscore, score);
2142 }
2143
2144 sumscore = sumscore*CHECK_COUNT/check_count;
2145 maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
2146
2147 av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2148
2149 if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2150 else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2151 else return -1;
2152}
2153
2154/* return the 90kHz PCR and the extension for the 27MHz PCR. return
2155 (-1) if not available */
2156static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2157 const uint8_t *packet)
2158{
2159 int afc, len, flags;
2160 const uint8_t *p;
2161 unsigned int v;
2162
2163 afc = (packet[3] >> 4) & 3;
2164 if (afc <= 1)
2165 return -1;
2166 p = packet + 4;
2167 len = p[0];
2168 p++;
2169 if (len == 0)
2170 return -1;
2171 flags = *p++;
2172 len--;
2173 if (!(flags & 0x10))
2174 return -1;
2175 if (len < 6)
2176 return -1;
2177 v = AV_RB32(p);
2178 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2179 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2180 return 0;
2181}
2182
2183static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2184
2185 /* NOTE: We attempt to seek on non-seekable files as well, as the
2186 * probe buffer usually is big enough. Only warn if the seek failed
2187 * on files where the seek should work. */
2188 if (avio_seek(pb, pos, SEEK_SET) < 0)
2189 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2190}
2191
2192static int mpegts_read_header(AVFormatContext *s)
2193{
2194 MpegTSContext *ts = s->priv_data;
2195 AVIOContext *pb = s->pb;
2196 uint8_t buf[8*1024]={0};
2197 int len;
2198 int64_t pos;
2199
2200 ts->first_pcrscr=AV_NOPTS_VALUE;
2201
2202 ffio_ensure_seekback(pb, s->probesize);
2203
2204 /* read the first 8192 bytes to get packet size */
2205 pos = avio_tell(pb);
2206 len = avio_read(pb, buf, sizeof(buf));
2207 ts->raw_packet_size = get_packet_size(buf, len);
2208 if (ts->raw_packet_size <= 0) {
2209 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2210 ts->raw_packet_size = TS_PACKET_SIZE;
2211 }
2212 ts->stream = s;
2213 ts->auto_guess = 0;
2214
2215 if (s->iformat == &ff_mpegts_demuxer) {
2216 /* normal demux */
2217
2218 /* first do a scan to get all the services */
2219 seek_back(s, pb, pos);
2220
2221 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2222
2223 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2224
2225 handle_packets(ts, s->probesize / ts->raw_packet_size);
2226 /* if could not find service, enable auto_guess */
2227
2228 ts->auto_guess = 1;
2229
2230 av_dlog(ts->stream, "tuning done\n");
2231
2232 s->ctx_flags |= AVFMTCTX_NOHEADER;
2233 } else {
2234 AVStream *st;
2235 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2236 int64_t pcrs[2], pcr_h;
2237 int packet_count[2];
2238 uint8_t packet[TS_PACKET_SIZE];
2239 const uint8_t *data;
2240
2241 /* only read packets */
2242
2243 st = avformat_new_stream(s, NULL);
2244 if (!st)
2245 goto fail;
2246 avpriv_set_pts_info(st, 60, 1, 27000000);
2247 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2248 st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2249
2250 /* we iterate until we find two PCRs to estimate the bitrate */
2251 pcr_pid = -1;
2252 nb_pcrs = 0;
2253 nb_packets = 0;
2254 for(;;) {
2255 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2256 if (ret < 0)
2257 goto fail;
2258 pid = AV_RB16(data + 1) & 0x1fff;
2259 if ((pcr_pid == -1 || pcr_pid == pid) &&
2260 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2261 finished_reading_packet(s, ts->raw_packet_size);
2262 pcr_pid = pid;
2263 packet_count[nb_pcrs] = nb_packets;
2264 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2265 nb_pcrs++;
2266 if (nb_pcrs >= 2)
2267 break;
2268 } else {
2269 finished_reading_packet(s, ts->raw_packet_size);
2270 }
2271 nb_packets++;
2272 }
2273
2274 /* NOTE1: the bitrate is computed without the FEC */
2275 /* NOTE2: it is only the bitrate of the start of the stream */
2276 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2277 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2278 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2279 st->codec->bit_rate = s->bit_rate;
2280 st->start_time = ts->cur_pcr;
2281 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2282 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2283 }
2284
2285 seek_back(s, pb, pos);
2286 return 0;
2287 fail:
2288 return -1;
2289}
2290
2291#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2292
2293static int mpegts_raw_read_packet(AVFormatContext *s,
2294 AVPacket *pkt)
2295{
2296 MpegTSContext *ts = s->priv_data;
2297 int ret, i;
2298 int64_t pcr_h, next_pcr_h, pos;
2299 int pcr_l, next_pcr_l;
2300 uint8_t pcr_buf[12];
2301 const uint8_t *data;
2302
2303 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2304 return AVERROR(ENOMEM);
2305 pkt->pos= avio_tell(s->pb);
2306 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2307 if (ret < 0) {
2308 av_free_packet(pkt);
2309 return ret;
2310 }
2311 if (data != pkt->data)
2312 memcpy(pkt->data, data, ts->raw_packet_size);
2313 finished_reading_packet(s, ts->raw_packet_size);
2314 if (ts->mpeg2ts_compute_pcr) {
2315 /* compute exact PCR for each packet */
2316 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2317 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2318 pos = avio_tell(s->pb);
2319 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2320 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2321 avio_read(s->pb, pcr_buf, 12);
2322 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2323 /* XXX: not precise enough */
2324 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2325 (i + 1);
2326 break;
2327 }
2328 }
2329 avio_seek(s->pb, pos, SEEK_SET);
2330 /* no next PCR found: we use previous increment */
2331 ts->cur_pcr = pcr_h * 300 + pcr_l;
2332 }
2333 pkt->pts = ts->cur_pcr;
2334 pkt->duration = ts->pcr_incr;
2335 ts->cur_pcr += ts->pcr_incr;
2336 }
2337 pkt->stream_index = 0;
2338 return 0;
2339}
2340
2341static int mpegts_read_packet(AVFormatContext *s,
2342 AVPacket *pkt)
2343{
2344 MpegTSContext *ts = s->priv_data;
2345 int ret, i;
2346
2347 pkt->size = -1;
2348 ts->pkt = pkt;
2349 ret = handle_packets(ts, 0);
2350 if (ret < 0) {
2351 av_free_packet(ts->pkt);
2352 /* flush pes data left */
2353 for (i = 0; i < NB_PID_MAX; i++) {
2354 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2355 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2356 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2357 new_pes_packet(pes, pkt);
2358 pes->state = MPEGTS_SKIP;
2359 ret = 0;
2360 break;
2361 }
2362 }
2363 }
2364 }
2365
2366 if (!ret && pkt->size < 0)
2367 ret = AVERROR(EINTR);
2368 return ret;
2369}
2370
2371static void mpegts_free(MpegTSContext *ts)
2372{
2373 int i;
2374
2375 clear_programs(ts);
2376
2377 for(i=0;i<NB_PID_MAX;i++)
2378 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2379}
2380
2381static int mpegts_read_close(AVFormatContext *s)
2382{
2383 MpegTSContext *ts = s->priv_data;
2384 mpegts_free(ts);
2385 return 0;
2386}
2387
2388static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2389 int64_t *ppos, int64_t pos_limit)
2390{
2391 MpegTSContext *ts = s->priv_data;
2392 int64_t pos, timestamp;
2393 uint8_t buf[TS_PACKET_SIZE];
2394 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2395 int pos47 = ts->pos47_full % ts->raw_packet_size;
2396 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2397 while(pos < pos_limit) {
2398 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2399 return AV_NOPTS_VALUE;
2400 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2401 return AV_NOPTS_VALUE;
2402 if (buf[0] != 0x47) {
2403 avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2404 if (mpegts_resync(s) < 0)
2405 return AV_NOPTS_VALUE;
2406 pos = avio_tell(s->pb);
2407 continue;
2408 }
2409 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2410 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2411 *ppos = pos;
2412 return timestamp;
2413 }
2414 pos += ts->raw_packet_size;
2415 }
2416
2417 return AV_NOPTS_VALUE;
2418}
2419
2420static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2421 int64_t *ppos, int64_t pos_limit)
2422{
2423 MpegTSContext *ts = s->priv_data;
2424 int64_t pos;
2425 int pos47 = ts->pos47_full % ts->raw_packet_size;
2426 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2427 ff_read_frame_flush(s);
2428 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2429 return AV_NOPTS_VALUE;
2430 while(pos < pos_limit) {
2431 int ret;
2432 AVPacket pkt;
2433 av_init_packet(&pkt);
2434 ret= av_read_frame(s, &pkt);
2435 if(ret < 0)
2436 return AV_NOPTS_VALUE;
2437 av_free_packet(&pkt);
2438 if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
2439 ff_reduce_index(s, pkt.stream_index);
2440 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2441 if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
2442 *ppos= pkt.pos;
2443 return pkt.dts;
2444 }
2445 }
2446 pos = pkt.pos;
2447 }
2448
2449 return AV_NOPTS_VALUE;
2450}
2451
2452static int read_seek2(AVFormatContext *s,
2453 int stream_index,
2454 int64_t min_ts,
2455 int64_t target_ts,
2456 int64_t max_ts,
2457 int flags)
2458{
2459 int64_t pos;
2460
2461 int64_t ts_ret, ts_adj;
2462 int stream_index_gen_search;
2463 AVStream *st;
2464 AVParserState *backup;
2465
2466 backup = ff_store_parser_state(s);
2467
2468 // detect direction of seeking for search purposes
2469 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
2470 AVSEEK_FLAG_BACKWARD : 0;
2471 av_log(NULL, AV_LOG_INFO, "read_seek::target_ts %lld , max_ts %lld ,flags %d streameindex %d\n", target_ts,max_ts,flags,stream_index);
2472 if (flags & AVSEEK_FLAG_BYTE) {
2473 // use position directly, we will search starting from it
2474 pos = target_ts;
2475 } else {
2476 // search for some position with good timestamp match
2477 if (stream_index < 0) {
2478 stream_index_gen_search = av_find_default_stream_index(s);
2479 av_log(NULL, AV_LOG_INFO, "read_seek::stream_index_gen_search %d\n", stream_index_gen_search);
2480 if (stream_index_gen_search < 0) {
2481 ff_restore_parser_state(s, backup);
2482 return -1;
2483 }
2484
2485 st = s->streams[stream_index_gen_search];
2486 // timestamp for default must be expressed in AV_TIME_BASE units
2487 ts_adj = av_rescale(target_ts,
2488 st->time_base.den,
2489 AV_TIME_BASE * (int64_t)st->time_base.num);
2490 } else {
2491 ts_adj = target_ts;
2492 stream_index_gen_search = stream_index;
2493 }
2494 pos = ff_gen_search(s, stream_index_gen_search, ts_adj,
2495 0, INT64_MAX, -1,
2496 AV_NOPTS_VALUE,
2497 AV_NOPTS_VALUE,
2498 flags, &ts_ret, mpegts_get_dts);
2499 av_log(NULL, AV_LOG_INFO, "read_seek::stream_index_gen_search %d ts_adj %lld pos %lld \n", stream_index_gen_search,ts_adj,pos);
2500 if (pos < 0) {
2501 ff_restore_parser_state(s, backup);
2502 return -1;
2503 }
2504 }
2505/* ==> modify by amlogic this is a slow when seek
2506 // search for actual matching keyframe/starting position for all streams
2507 if (ff_gen_syncpoint_search(s, stream_index, pos,
2508 min_ts, target_ts, max_ts,
2509 flags) < 0) {
2510 ff_restore_parser_state(s, backup);
2511 return -1;
2512 }
2513*/
2514 avio_seek(s->pb, pos, SEEK_SET);
2515 ff_free_parser_state(s, backup);
2516 return 0;
2517}
2518
2519static int mpegts_read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
2520 int ret;
2521 if (flags & AVSEEK_FLAG_BACKWARD) {
2522 flags &= ~AVSEEK_FLAG_BACKWARD;
2523 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
2524 if (ret < 0) {
2525 // for compatibility reasons, seek to the best-fitting timestamp
2526 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
2527 }
2528 } else {
2529 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
2530 if (ret < 0)
2531 // for compatibility reasons, seek to the best-fitting timestamp
2532 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
2533 }
2534 return ret;
2535}
2536
2537
2538/**************************************************************/
2539/* parsing functions - called from other demuxers such as RTP */
2540
2541MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2542{
2543 MpegTSContext *ts;
2544
2545 ts = av_mallocz(sizeof(MpegTSContext));
2546 if (!ts)
2547 return NULL;
2548 /* no stream case, currently used by RTP */
2549 ts->raw_packet_size = TS_PACKET_SIZE;
2550 ts->stream = s;
2551 ts->auto_guess = 1;
2552 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2553 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2554
2555 return ts;
2556}
2557
2558/* return the consumed length if a packet was output, or -1 if no
2559 packet is output */
2560int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2561 const uint8_t *buf, int len)
2562{
2563 int len1;
2564
2565 len1 = len;
2566 ts->pkt = pkt;
2567 for(;;) {
2568 ts->stop_parse = 0;
2569 if (len < TS_PACKET_SIZE)
2570 return -1;
2571 if (buf[0] != 0x47) {
2572 buf++;
2573 len--;
2574 } else {
2575 handle_packet(ts, buf);
2576 buf += TS_PACKET_SIZE;
2577 len -= TS_PACKET_SIZE;
2578 if (ts->stop_parse == 1)
2579 break;
2580 }
2581 }
2582 return len1 - len;
2583}
2584
2585void ff_mpegts_parse_close(MpegTSContext *ts)
2586{
2587 mpegts_free(ts);
2588 av_free(ts);
2589}
2590
2591AVInputFormat ff_mpegts_demuxer = {
2592 .name = "mpegts",
2593 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2594 .priv_data_size = sizeof(MpegTSContext),
2595 .read_probe = mpegts_probe,
2596 .read_header = mpegts_read_header,
2597 .read_packet = mpegts_read_packet,
2598 .read_close = mpegts_read_close,
2599 .read_seek = mpegts_read_seek,
2600 .read_timestamp = mpegts_get_dts,
2601 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT | AVFMT_GENERIC_INDEX,
2602 .priv_class = &mpegts_class,
2603};
2604
2605AVInputFormat ff_mpegtsraw_demuxer = {
2606 .name = "mpegtsraw",
2607 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2608 .priv_data_size = sizeof(MpegTSContext),
2609 .read_header = mpegts_read_header,
2610 .read_packet = mpegts_raw_read_packet,
2611 .read_close = mpegts_read_close,
2612 .read_seek = mpegts_read_seek,
2613 .read_timestamp = mpegts_get_dts,
2614 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT | AVFMT_GENERIC_INDEX,
2615 .priv_class = &mpegtsraw_class,
2616};
2617