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