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