FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/mpegts.c
Date: 2026-05-05 13:32:37
Exec Total Coverage
Lines: 0 2099 0.0%
Functions: 0 72 0.0%
Branches: 0 1418 0.0%

Line Branch Exec Source
1 /*
2 * MPEG-2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "config_components.h"
23
24 #include "libavutil/attributes_internal.h"
25 #include "libavutil/buffer.h"
26 #include "libavutil/crc.h"
27 #include "libavutil/internal.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/log.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/dovi_meta.h"
35 #include "libavcodec/bytestream.h"
36 #include "libavcodec/defs.h"
37 #include "libavcodec/get_bits.h"
38 #include "libavcodec/opus/opus.h"
39 #include "avformat.h"
40 #include "mpegts.h"
41 #include "internal.h"
42 #include "avio_internal.h"
43 #include "demux.h"
44 #include "mpeg.h"
45 #include "isom.h"
46 #if CONFIG_ICONV
47 #include <iconv.h>
48 #endif
49
50 /* maximum size in which we look for synchronization if
51 * synchronization is lost */
52 #define MAX_RESYNC_SIZE 65536
53
54 #define MAX_MP4_DESCR_COUNT 16
55
56 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
57 do { \
58 if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
59 (modulus) = (dividend) % (divisor); \
60 (prev_dividend) = (dividend); \
61 } while (0)
62
63 #define PROBE_PACKET_MAX_BUF 8192
64 #define PROBE_PACKET_MARGIN 5
65
66 enum MpegTSFilterType {
67 MPEGTS_PES,
68 MPEGTS_SECTION,
69 MPEGTS_PCR,
70 };
71
72 typedef struct MpegTSFilter MpegTSFilter;
73
74 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
75 int is_start, int64_t pos);
76
77 typedef struct MpegTSPESFilter {
78 PESCallback *pes_cb;
79 void *opaque;
80 } MpegTSPESFilter;
81
82 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
83
84 typedef void SetServiceCallback (void *opaque, int ret);
85
86 typedef struct MpegTSSectionFilter {
87 int section_index;
88 int section_h_size;
89 int last_ver;
90 unsigned crc;
91 unsigned last_crc;
92 uint8_t *section_buf;
93 unsigned int check_crc : 1;
94 unsigned int end_of_section_reached : 1;
95 SectionCallback *section_cb;
96 void *opaque;
97 } MpegTSSectionFilter;
98
99 struct MpegTSFilter {
100 int pid;
101 int es_id;
102 int last_cc; /* last cc code (-1 if first packet) */
103 int64_t last_pcr;
104 int discard;
105 enum MpegTSFilterType type;
106 union {
107 MpegTSPESFilter pes_filter;
108 MpegTSSectionFilter section_filter;
109 } u;
110 };
111
112 struct Stream {
113 int idx;
114 int stream_identifier;
115 };
116
117 #define MAX_STREAMS_PER_PROGRAM 128
118 #define MAX_PIDS_PER_PROGRAM (MAX_STREAMS_PER_PROGRAM + 2)
119
120 struct StreamGroup {
121 enum AVStreamGroupParamsType type;
122 int id;
123 unsigned int nb_streams;
124 AVStream *streams[MAX_STREAMS_PER_PROGRAM];
125 };
126
127 struct Program {
128 unsigned int id; // program id/service id
129 unsigned int nb_pids;
130 unsigned int pids[MAX_PIDS_PER_PROGRAM];
131 unsigned int nb_streams;
132 struct Stream streams[MAX_STREAMS_PER_PROGRAM];
133 unsigned int nb_stream_groups;
134 struct StreamGroup stream_groups[MAX_STREAMS_PER_PROGRAM];
135
136 /** have we found pmt for this program */
137 int pmt_found;
138 };
139
140 struct MpegTSContext {
141 const AVClass *class;
142 /* user data */
143 AVFormatContext *stream;
144 /** raw packet size, including FEC if present */
145 int raw_packet_size;
146
147 int64_t pos47_full;
148
149 /** if true, all pids are analyzed to find streams */
150 int auto_guess;
151
152 /** compute exact PCR for each transport stream packet */
153 int mpeg2ts_compute_pcr;
154
155 /** fix dvb teletext pts */
156 int fix_teletext_pts;
157
158 int64_t cur_pcr; /**< used to estimate the exact PCR */
159 int64_t pcr_incr; /**< used to estimate the exact PCR */
160
161 /* data needed to handle file based ts */
162 /** stop parsing loop */
163 int stop_parse;
164 /** packet containing Audio/Video data */
165 AVPacket *pkt;
166 /** to detect seek */
167 int64_t last_pos;
168
169 int skip_changes;
170 int skip_clear;
171 int skip_unknown_pmt;
172
173 int scan_all_pmts;
174
175 int resync_size;
176 int merge_pmt_versions;
177 int max_packet_size;
178
179 int id;
180
181 /******************************************/
182 /* private mpegts data */
183 /* scan context */
184 /** structure to keep track of Program->pids mapping */
185 unsigned int nb_prg;
186 struct Program *prg;
187
188 int8_t crc_validity[NB_PID_MAX];
189 /** filters for various streams specified by PMT + for the PAT and PMT */
190 MpegTSFilter *pids[NB_PID_MAX];
191 int current_pid;
192
193 AVStream *epg_stream;
194 AVBufferPool* pools[32];
195 };
196
197 #define MPEGTS_OPTIONS \
198 { "resync_size", "set size limit for looking up a new synchronization", \
199 offsetof(MpegTSContext, resync_size), AV_OPT_TYPE_INT, \
200 { .i64 = MAX_RESYNC_SIZE}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM }, \
201 { "ts_id", "transport stream id", \
202 offsetof(MpegTSContext, id), AV_OPT_TYPE_INT, \
203 { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }, \
204 { "ts_packetsize", "output option carrying the raw packet size", \
205 offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT, \
206 { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }
207
208 static const AVOption options[] = {
209 MPEGTS_OPTIONS,
210 {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
211 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
212 {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
213 {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
214 {"skip_unknown_pmt", "skip PMTs for programs not advertised in the PAT", offsetof(MpegTSContext, skip_unknown_pmt), AV_OPT_TYPE_BOOL,
215 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
216 {"merge_pmt_versions", "reuse streams when PMT's version/pids change", offsetof(MpegTSContext, merge_pmt_versions), AV_OPT_TYPE_BOOL,
217 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
218 {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
219 {.i64 = 0}, 0, 1, 0 },
220 {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
221 {.i64 = 0}, 0, 1, 0 },
222 {"max_packet_size", "maximum size of emitted packet", offsetof(MpegTSContext, max_packet_size), AV_OPT_TYPE_INT,
223 {.i64 = 204800}, 1, INT_MAX/2, AV_OPT_FLAG_DECODING_PARAM },
224 { NULL },
225 };
226
227 static const AVClass mpegts_class = {
228 .class_name = "mpegts demuxer",
229 .item_name = av_default_item_name,
230 .option = options,
231 .version = LIBAVUTIL_VERSION_INT,
232 };
233
234 static const AVOption raw_options[] = {
235 MPEGTS_OPTIONS,
236 { "compute_pcr", "compute exact PCR for each transport stream packet",
237 offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
238 { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
239 { NULL },
240 };
241
242 static const AVClass mpegtsraw_class = {
243 .class_name = "mpegtsraw demuxer",
244 .item_name = av_default_item_name,
245 .option = raw_options,
246 .version = LIBAVUTIL_VERSION_INT,
247 };
248
249 /* TS stream handling */
250
251 enum MpegTSState {
252 MPEGTS_HEADER = 0,
253 MPEGTS_PESHEADER,
254 MPEGTS_PESHEADER_FILL,
255 MPEGTS_PAYLOAD,
256 MPEGTS_SKIP,
257 };
258
259 /* enough for PES header + length */
260 #define PES_START_SIZE 6
261 #define PES_HEADER_SIZE 9
262 #define MAX_PES_HEADER_SIZE (9 + 255)
263
264 typedef struct PESContext {
265 int pid;
266 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
267 int stream_type;
268 MpegTSContext *ts;
269 AVFormatContext *stream;
270 AVStream *st;
271 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
272 enum MpegTSState state;
273 /* used to get the format */
274 int data_index;
275 int flags; /**< copied to the AVPacket flags */
276 int PES_packet_length;
277 int pes_header_size;
278 int extended_stream_id;
279 uint8_t stream_id;
280 int64_t pts, dts;
281 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
282 uint8_t header[MAX_PES_HEADER_SIZE];
283 AVBufferRef *buffer;
284 SLConfigDescr sl;
285 int merged_st;
286 } PESContext;
287
288 EXTERN const FFInputFormat ff_mpegts_demuxer;
289
290 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
291 {
292 int i;
293 for (i = 0; i < ts->nb_prg; i++) {
294 if (ts->prg[i].id == programid) {
295 return &ts->prg[i];
296 }
297 }
298 return NULL;
299 }
300
301 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
302 {
303 AVProgram *prg = NULL;
304 int i;
305
306 for (i = 0; i < ts->stream->nb_programs; i++)
307 if (ts->stream->programs[i]->id == programid) {
308 prg = ts->stream->programs[i];
309 break;
310 }
311 if (!prg)
312 return;
313 prg->nb_stream_indexes = 0;
314 }
315
316 static void clear_program(struct Program *p)
317 {
318 if (!p)
319 return;
320 p->nb_pids = 0;
321 p->nb_streams = 0;
322 p->nb_stream_groups = 0;
323 memset(p->stream_groups, 0, sizeof(p->stream_groups));
324 p->pmt_found = 0;
325 }
326
327 static void clear_programs(MpegTSContext *ts)
328 {
329 av_freep(&ts->prg);
330 ts->nb_prg = 0;
331 }
332
333 static struct Program * add_program(MpegTSContext *ts, unsigned int programid)
334 {
335 struct Program *p = get_program(ts, programid);
336 if (p)
337 return p;
338 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
339 ts->nb_prg = 0;
340 return NULL;
341 }
342 p = &ts->prg[ts->nb_prg];
343 p->id = programid;
344 clear_program(p);
345 ts->nb_prg++;
346 return p;
347 }
348
349 static void add_pid_to_program(struct Program *p, unsigned int pid)
350 {
351 int i;
352 if (!p)
353 return;
354
355 if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
356 return;
357
358 for (i = 0; i < p->nb_pids; i++)
359 if (p->pids[i] == pid)
360 return;
361
362 p->pids[p->nb_pids++] = pid;
363 }
364
365 static void update_av_program_info(AVFormatContext *s, unsigned int programid,
366 unsigned int pid, int version)
367 {
368 int i;
369 for (i = 0; i < s->nb_programs; i++) {
370 AVProgram *program = s->programs[i];
371 if (program->id == programid) {
372 int old_pcr_pid = program->pcr_pid,
373 old_version = program->pmt_version;
374 program->pcr_pid = pid;
375 program->pmt_version = version;
376
377 if (old_version != -1 && old_version != version) {
378 av_log(s, AV_LOG_VERBOSE,
379 "detected PMT change (program=%d, version=%d/%d, pcr_pid=0x%x/0x%x)\n",
380 programid, old_version, version, old_pcr_pid, pid);
381 }
382 break;
383 }
384 }
385 }
386
387 /**
388 * @brief discard_pid() decides if the pid is to be discarded according
389 * to caller's programs selection
390 * @param ts : - TS context
391 * @param pid : - pid
392 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
393 * 0 otherwise
394 */
395 static int discard_pid(MpegTSContext *ts, unsigned int pid)
396 {
397 int i, j, k;
398 int used = 0, discarded = 0;
399 struct Program *p;
400
401 if (pid == PAT_PID)
402 return 0;
403
404 /* If none of the programs have .discard=AVDISCARD_ALL then there's
405 * no way we have to discard this packet */
406 for (k = 0; k < ts->stream->nb_programs; k++)
407 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
408 break;
409 if (k == ts->stream->nb_programs)
410 return 0;
411
412 for (i = 0; i < ts->nb_prg; i++) {
413 p = &ts->prg[i];
414 for (j = 0; j < p->nb_pids; j++) {
415 if (p->pids[j] != pid)
416 continue;
417 // is program with id p->id set to be discarded?
418 for (k = 0; k < ts->stream->nb_programs; k++) {
419 if (ts->stream->programs[k]->id == p->id) {
420 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
421 discarded++;
422 else
423 used++;
424 }
425 }
426 }
427 }
428
429 return !used && discarded;
430 }
431
432 /**
433 * Assemble PES packets out of TS packets, and then call the "section_cb"
434 * function when they are complete.
435 */
436 static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
437 const uint8_t *buf, int buf_size, int is_start)
438 {
439 MpegTSSectionFilter *tss = &tss1->u.section_filter;
440 uint8_t *cur_section_buf = NULL;
441 int len, offset;
442
443 if (is_start) {
444 memcpy(tss->section_buf, buf, buf_size);
445 tss->section_index = buf_size;
446 tss->section_h_size = -1;
447 tss->end_of_section_reached = 0;
448 } else {
449 if (tss->end_of_section_reached)
450 return;
451 len = MAX_SECTION_SIZE - tss->section_index;
452 if (buf_size < len)
453 len = buf_size;
454 memcpy(tss->section_buf + tss->section_index, buf, len);
455 tss->section_index += len;
456 }
457
458 offset = 0;
459 cur_section_buf = tss->section_buf;
460 while (cur_section_buf - tss->section_buf < MAX_SECTION_SIZE && cur_section_buf[0] != STUFFING_BYTE) {
461 /* compute section length if possible */
462 if (tss->section_h_size == -1 && tss->section_index - offset >= 3) {
463 len = (AV_RB16(cur_section_buf + 1) & 0xfff) + 3;
464 if (len > MAX_SECTION_SIZE)
465 return;
466 tss->section_h_size = len;
467 }
468
469 if (tss->section_h_size != -1 &&
470 tss->section_index >= offset + tss->section_h_size) {
471 int crc_valid = 1;
472 tss->end_of_section_reached = 1;
473
474 if (tss->check_crc) {
475 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, cur_section_buf, tss->section_h_size);
476 if (tss->section_h_size >= 4)
477 tss->crc = AV_RB32(cur_section_buf + tss->section_h_size - 4);
478
479 if (crc_valid) {
480 ts->crc_validity[ tss1->pid ] = 100;
481 }else if (ts->crc_validity[ tss1->pid ] > -10) {
482 ts->crc_validity[ tss1->pid ]--;
483 }else
484 crc_valid = 2;
485 }
486 if (crc_valid) {
487 tss->section_cb(tss1, cur_section_buf, tss->section_h_size);
488 if (crc_valid != 1)
489 tss->last_ver = -1;
490 }
491
492 cur_section_buf += tss->section_h_size;
493 offset += tss->section_h_size;
494 tss->section_h_size = -1;
495 } else {
496 tss->section_h_size = -1;
497 tss->end_of_section_reached = 0;
498 break;
499 }
500 }
501 }
502
503 static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
504 enum MpegTSFilterType type)
505 {
506 MpegTSFilter *filter;
507
508 av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
509
510 if (pid >= NB_PID_MAX || ts->pids[pid])
511 return NULL;
512 filter = av_mallocz(sizeof(MpegTSFilter));
513 if (!filter)
514 return NULL;
515 ts->pids[pid] = filter;
516
517 filter->type = type;
518 filter->pid = pid;
519 filter->es_id = -1;
520 filter->last_cc = -1;
521 filter->last_pcr= -1;
522
523 return filter;
524 }
525
526 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
527 unsigned int pid,
528 SectionCallback *section_cb,
529 void *opaque,
530 int check_crc)
531 {
532 MpegTSFilter *filter;
533 MpegTSSectionFilter *sec;
534 uint8_t *section_buf = av_mallocz(MAX_SECTION_SIZE);
535
536 if (!section_buf)
537 return NULL;
538
539 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION))) {
540 av_free(section_buf);
541 return NULL;
542 }
543 sec = &filter->u.section_filter;
544 sec->section_cb = section_cb;
545 sec->opaque = opaque;
546 sec->section_buf = section_buf;
547 sec->check_crc = check_crc;
548 sec->last_ver = -1;
549
550 return filter;
551 }
552
553 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
554 PESCallback *pes_cb,
555 void *opaque)
556 {
557 MpegTSFilter *filter;
558 MpegTSPESFilter *pes;
559
560 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
561 return NULL;
562
563 pes = &filter->u.pes_filter;
564 pes->pes_cb = pes_cb;
565 pes->opaque = opaque;
566 return filter;
567 }
568
569 static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
570 {
571 return mpegts_open_filter(ts, pid, MPEGTS_PCR);
572 }
573
574 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
575 {
576 int pid;
577
578 pid = filter->pid;
579 if (filter->type == MPEGTS_SECTION)
580 av_freep(&filter->u.section_filter.section_buf);
581 else if (filter->type == MPEGTS_PES) {
582 PESContext *pes = filter->u.pes_filter.opaque;
583 av_buffer_unref(&pes->buffer);
584 /* referenced private data will be freed later in
585 * avformat_close_input (pes->st->priv_data == pes) */
586 if (!pes->st || pes->merged_st || !pes->st->priv_data) {
587 av_freep(&filter->u.pes_filter.opaque);
588 }
589 }
590
591 av_free(filter);
592 ts->pids[pid] = NULL;
593 }
594
595 static int analyze(const uint8_t *buf, int size, int packet_size,
596 int probe)
597 {
598 int stat[TS_MAX_PACKET_SIZE];
599 int stat_all = 0;
600 int i;
601 int best_score = 0;
602
603 memset(stat, 0, packet_size * sizeof(*stat));
604
605 for (i = 0; i < size - 3; i++) {
606 if (buf[i] == SYNC_BYTE) {
607 int pid = AV_RB16(buf+1) & 0x1FFF;
608 int asc = buf[i + 3] & 0x30;
609 if (!probe || pid == 0x1FFF || asc) {
610 int x = i % packet_size;
611 stat[x]++;
612 stat_all++;
613 if (stat[x] > best_score) {
614 best_score = stat[x];
615 }
616 }
617 }
618 }
619
620 return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
621 }
622
623 /* autodetect fec presence */
624 static int get_packet_size(AVFormatContext* s)
625 {
626 int score, fec_score, dvhs_score;
627 int margin;
628 int ret;
629
630 /*init buffer to store stream for probing */
631 uint8_t buf[PROBE_PACKET_MAX_BUF] = {0};
632 int buf_size = 0;
633 int max_iterations = 16;
634
635 while (buf_size < PROBE_PACKET_MAX_BUF && max_iterations--) {
636 ret = avio_read_partial(s->pb, buf + buf_size, PROBE_PACKET_MAX_BUF - buf_size);
637 if (ret < 0)
638 return AVERROR_INVALIDDATA;
639 buf_size += ret;
640
641 score = analyze(buf, buf_size, TS_PACKET_SIZE, 0);
642 dvhs_score = analyze(buf, buf_size, TS_DVHS_PACKET_SIZE, 0);
643 fec_score = analyze(buf, buf_size, TS_FEC_PACKET_SIZE, 0);
644 av_log(s, AV_LOG_TRACE, "Probe: %d, score: %d, dvhs_score: %d, fec_score: %d \n",
645 buf_size, score, dvhs_score, fec_score);
646
647 margin = mid_pred(score, fec_score, dvhs_score);
648
649 if (buf_size < PROBE_PACKET_MAX_BUF)
650 margin += PROBE_PACKET_MARGIN; /*if buffer not filled */
651
652 if (score > margin)
653 return TS_PACKET_SIZE;
654 else if (dvhs_score > margin)
655 return TS_DVHS_PACKET_SIZE;
656 else if (fec_score > margin)
657 return TS_FEC_PACKET_SIZE;
658 }
659 return AVERROR_INVALIDDATA;
660 }
661
662 typedef struct SectionHeader {
663 uint8_t tid;
664 uint16_t id;
665 uint8_t version;
666 uint8_t current_next;
667 uint8_t sec_num;
668 uint8_t last_sec_num;
669 } SectionHeader;
670
671 static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
672 {
673 if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
674 return 1;
675
676 tssf->last_ver = h->version;
677 tssf->last_crc = tssf->crc;
678
679 return 0;
680 }
681
682 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
683 {
684 const uint8_t *p;
685 int c;
686
687 p = *pp;
688 if (p >= p_end)
689 return AVERROR_INVALIDDATA;
690 c = *p++;
691 *pp = p;
692 return c;
693 }
694
695 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
696 {
697 const uint8_t *p;
698 int c;
699
700 p = *pp;
701 if (1 >= p_end - p)
702 return AVERROR_INVALIDDATA;
703 c = AV_RB16(p);
704 p += 2;
705 *pp = p;
706 return c;
707 }
708
709 /* read and allocate a DVB string preceded by its length */
710 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
711 {
712 int len;
713 const uint8_t *p;
714 char *str;
715
716 p = *pp;
717 len = get8(&p, p_end);
718 if (len < 0)
719 return NULL;
720 if (len > p_end - p)
721 return NULL;
722 #if CONFIG_ICONV
723 if (len) {
724 const char *encodings[] = {
725 "ISO6937", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7",
726 "ISO-8859-8", "ISO-8859-9", "ISO-8859-10", "ISO-8859-11",
727 "", "ISO-8859-13", "ISO-8859-14", "ISO-8859-15", "", "", "", "",
728 "", "UCS-2BE", "KSC_5601", "GB2312", "UCS-2BE", "UTF-8", "", "",
729 "", "", "", "", "", "", "", ""
730 };
731 iconv_t cd;
732 char *in, *out;
733 size_t inlen = len, outlen = inlen * 6 + 1;
734 if (len >= 3 && p[0] == 0x10 && !p[1] && p[2] && p[2] <= 0xf && p[2] != 0xc) {
735 char iso8859[12];
736 snprintf(iso8859, sizeof(iso8859), "ISO-8859-%d", p[2]);
737 inlen -= 3;
738 in = (char *)p + 3;
739 cd = iconv_open("UTF-8", iso8859);
740 } else if (p[0] < 0x20) {
741 inlen -= 1;
742 in = (char *)p + 1;
743 cd = iconv_open("UTF-8", encodings[*p]);
744 } else {
745 in = (char *)p;
746 cd = iconv_open("UTF-8", encodings[0]);
747 }
748 if (cd == (iconv_t)-1)
749 goto no_iconv;
750 str = out = av_malloc(outlen);
751 if (!str) {
752 iconv_close(cd);
753 return NULL;
754 }
755 if (iconv(cd, &in, &inlen, &out, &outlen) == -1) {
756 iconv_close(cd);
757 av_freep(&str);
758 goto no_iconv;
759 }
760 iconv_close(cd);
761 *out = 0;
762 *pp = p + len;
763 return str;
764 }
765 no_iconv:
766 #endif
767 str = av_malloc(len + 1);
768 if (!str)
769 return NULL;
770 memcpy(str, p, len);
771 str[len] = '\0';
772 p += len;
773 *pp = p;
774 return str;
775 }
776
777 static int parse_section_header(SectionHeader *h,
778 const uint8_t **pp, const uint8_t *p_end)
779 {
780 int val;
781
782 val = get8(pp, p_end);
783 if (val < 0)
784 return val;
785 h->tid = val;
786 *pp += 2;
787 val = get16(pp, p_end);
788 if (val < 0)
789 return val;
790 h->id = val;
791 val = get8(pp, p_end);
792 if (val < 0)
793 return val;
794 h->version = (val >> 1) & 0x1f;
795 h->current_next = val & 0x01;
796 val = get8(pp, p_end);
797 if (val < 0)
798 return val;
799 h->sec_num = val;
800 val = get8(pp, p_end);
801 if (val < 0)
802 return val;
803 h->last_sec_num = val;
804 return 0;
805 }
806
807 typedef struct StreamType {
808 uint32_t stream_type;
809 enum AVMediaType codec_type;
810 enum AVCodecID codec_id;
811 } StreamType;
812
813 static const StreamType ISO_types[] = {
814 { STREAM_TYPE_VIDEO_MPEG1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
815 { STREAM_TYPE_VIDEO_MPEG2, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
816 { STREAM_TYPE_AUDIO_MPEG1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
817 { STREAM_TYPE_AUDIO_MPEG2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
818 { STREAM_TYPE_AUDIO_AAC, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
819 { STREAM_TYPE_VIDEO_MPEG4, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
820 /* Makito encoder sets stream type 0x11 for AAC,
821 * so auto-detect LOAS/LATM instead of hardcoding it. */
822 #if !CONFIG_LOAS_DEMUXER
823 { STREAM_TYPE_AUDIO_AAC_LATM, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
824 #endif
825 { STREAM_TYPE_VIDEO_H264, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
826 { STREAM_TYPE_AUDIO_MPEG4, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
827 { STREAM_TYPE_VIDEO_MVC, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
828 { STREAM_TYPE_VIDEO_JPEG2000, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000 },
829 { STREAM_TYPE_VIDEO_HEVC, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
830 { STREAM_TYPE_VIDEO_JPEGXS, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEGXS },
831 { STREAM_TYPE_VIDEO_LCEVC, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_LCEVC },
832 { STREAM_TYPE_VIDEO_VVC, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VVC },
833 { STREAM_TYPE_VIDEO_CAVS, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
834 { STREAM_TYPE_VIDEO_DIRAC, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
835 { STREAM_TYPE_VIDEO_AVS2, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_AVS2 },
836 { STREAM_TYPE_VIDEO_AVS3, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_AVS3 },
837 { STREAM_TYPE_VIDEO_VC1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
838 { 0 },
839 };
840
841 static const StreamType HDMV_types[] = {
842 { STREAM_TYPE_BLURAY_AUDIO_PCM_BLURAY, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
843 { STREAM_TYPE_BLURAY_AUDIO_AC3, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
844 { STREAM_TYPE_BLURAY_AUDIO_DTS, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
845 { STREAM_TYPE_BLURAY_AUDIO_TRUEHD, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
846 { STREAM_TYPE_BLURAY_AUDIO_EAC3, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
847 { STREAM_TYPE_BLURAY_AUDIO_DTS_HD, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
848 { STREAM_TYPE_BLURAY_AUDIO_DTS_HD_MASTER, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
849 { STREAM_TYPE_BLURAY_AUDIO_EAC3_SECONDARY, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
850 { STREAM_TYPE_BLURAY_AUDIO_DTS_EXPRESS_SECONDARY, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
851 { STREAM_TYPE_BLURAY_SUBTITLE_PGS, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
852 { STREAM_TYPE_BLURAY_SUBTITLE_TEXT, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
853 { 0 },
854 };
855
856 /* SCTE types */
857 static const StreamType SCTE_types[] = {
858 { STREAM_TYPE_SCTE_DATA_SCTE_35, AVMEDIA_TYPE_DATA, AV_CODEC_ID_SCTE_35 },
859 { 0 },
860 };
861
862 /* ATSC ? */
863 static const StreamType MISC_types[] = {
864 { STREAM_TYPE_ATSC_AUDIO_AC3, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
865 { STREAM_TYPE_ATSC_AUDIO_EAC3, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
866 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
867 { 0 },
868 };
869
870 /* HLS Sample Encryption Types */
871 static const StreamType HLS_SAMPLE_ENC_types[] = {
872 { STREAM_TYPE_HLS_SE_VIDEO_H264, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264},
873 { STREAM_TYPE_HLS_SE_AUDIO_AAC, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
874 { STREAM_TYPE_HLS_SE_AUDIO_AC3, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
875 { STREAM_TYPE_HLS_SE_AUDIO_EAC3, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3},
876 { 0 },
877 };
878
879 static const StreamType REGD_types[] = {
880 { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
881 { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
882 { MKTAG('A', 'C', '-', '4'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC4 },
883 { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
884 { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
885 { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
886 { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
887 { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
888 { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
889 { MKTAG('V', 'V', 'C', ' '), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VVC },
890 { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
891 { MKTAG('V', 'A', 'N', 'C'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_2038 },
892 { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
893 { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
894 { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
895 { 0 },
896 };
897
898 static const StreamType METADATA_types[] = {
899 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
900 { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
901 { 0 },
902 };
903
904 /* descriptor present */
905 static const StreamType DESC_types[] = {
906 { AC3_DESCRIPTOR, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
907 { ENHANCED_AC3_DESCRIPTOR, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
908 { DTS_DESCRIPTOR, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
909 { TELETEXT_DESCRIPTOR, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
910 { SUBTITLING_DESCRIPTOR, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE },
911 { 0 },
912 };
913
914 static void mpegts_find_stream_type(AVStream *st,
915 uint32_t stream_type,
916 const StreamType *types)
917 {
918 FFStream *const sti = ffstream(st);
919 for (; types->stream_type; types++)
920 if (stream_type == types->stream_type) {
921 if (st->codecpar->codec_type != types->codec_type ||
922 st->codecpar->codec_id != types->codec_id) {
923 st->codecpar->codec_type = types->codec_type;
924 st->codecpar->codec_id = types->codec_id;
925 sti->need_context_update = 1;
926 }
927 sti->request_probe = 0;
928 return;
929 }
930 }
931
932 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
933 uint32_t stream_type, uint32_t prog_reg_desc)
934 {
935 FFStream *const sti = ffstream(st);
936 int old_codec_type = st->codecpar->codec_type;
937 int old_codec_id = st->codecpar->codec_id;
938 int old_codec_tag = st->codecpar->codec_tag;
939
940 avpriv_set_pts_info(st, 33, 1, 90000);
941 st->priv_data = pes;
942 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
943 st->codecpar->codec_id = AV_CODEC_ID_NONE;
944 sti->need_parsing = AVSTREAM_PARSE_FULL;
945 pes->st = st;
946 pes->stream_type = stream_type;
947
948 av_log(pes->stream, AV_LOG_DEBUG,
949 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
950 st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
951
952 st->codecpar->codec_tag = pes->stream_type;
953
954 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
955 if (pes->stream_type == STREAM_TYPE_AUDIO_MPEG2 || pes->stream_type == STREAM_TYPE_AUDIO_AAC)
956 sti->request_probe = 50;
957 if (pes->stream_type == STREAM_TYPE_PRIVATE_DATA)
958 sti->request_probe = AVPROBE_SCORE_STREAM_RETRY;
959 if ((prog_reg_desc == AV_RL32("HDMV") ||
960 prog_reg_desc == AV_RL32("HDPR")) &&
961 st->codecpar->codec_id == AV_CODEC_ID_NONE) {
962 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
963 if (pes->stream_type == STREAM_TYPE_BLURAY_AUDIO_TRUEHD) {
964 // HDMV TrueHD streams also contain an AC3 coded version of the
965 // audio track - add a second stream for this
966 AVStream *sub_st;
967 // priv_data cannot be shared between streams
968 PESContext *sub_pes = av_memdup(pes, sizeof(*sub_pes));
969 if (!sub_pes)
970 return AVERROR(ENOMEM);
971
972 sub_st = avformat_new_stream(pes->stream, NULL);
973 if (!sub_st) {
974 av_free(sub_pes);
975 return AVERROR(ENOMEM);
976 }
977
978 sub_st->id = pes->pid;
979 avpriv_set_pts_info(sub_st, 33, 1, 90000);
980 sub_st->priv_data = sub_pes;
981 sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
982 sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
983 ffstream(sub_st)->need_parsing = AVSTREAM_PARSE_FULL;
984 sub_pes->sub_st = pes->sub_st = sub_st;
985 }
986 }
987 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
988 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
989 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
990 mpegts_find_stream_type(st, pes->stream_type, HLS_SAMPLE_ENC_types);
991 if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
992 st->codecpar->codec_id = old_codec_id;
993 st->codecpar->codec_type = old_codec_type;
994 }
995 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
996 (sti->request_probe > 0 && sti->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
997 sti->probe_packets > 0 &&
998 stream_type == STREAM_TYPE_PRIVATE_DATA) {
999 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
1000 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
1001 sti->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
1002 }
1003
1004 /* queue a context update if properties changed */
1005 if (old_codec_type != st->codecpar->codec_type ||
1006 old_codec_id != st->codecpar->codec_id ||
1007 old_codec_tag != st->codecpar->codec_tag)
1008 sti->need_context_update = 1;
1009
1010 return 0;
1011 }
1012
1013 static void reset_pes_packet_state(PESContext *pes)
1014 {
1015 pes->pts = AV_NOPTS_VALUE;
1016 pes->dts = AV_NOPTS_VALUE;
1017 pes->data_index = 0;
1018 pes->flags = 0;
1019 av_buffer_unref(&pes->buffer);
1020 }
1021
1022 static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
1023 {
1024 av_packet_unref(pkt);
1025 pkt->data = (uint8_t *)buffer;
1026 pkt->size = len;
1027 }
1028
1029 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
1030 {
1031 uint8_t *sd;
1032
1033 av_packet_unref(pkt);
1034
1035 pkt->buf = pes->buffer;
1036 pkt->data = pes->buffer->data;
1037 pkt->size = pes->data_index;
1038
1039 if (pes->PES_packet_length &&
1040 pes->pes_header_size + pes->data_index != pes->PES_packet_length +
1041 PES_START_SIZE) {
1042 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
1043 pes->flags |= AV_PKT_FLAG_CORRUPT;
1044 }
1045
1046 // JPEG-XS PES payload
1047 if (pes->stream_id == 0xbd && pes->stream_type == 0x32 &&
1048 pkt->size >= 8 && memcmp(pkt->data + 4, "jxes", 4) == 0)
1049 {
1050 uint32_t header_size = AV_RB32(pkt->data);
1051 if (header_size > pkt->size) {
1052 av_log(pes->stream, AV_LOG_WARNING,
1053 "Invalid JPEG-XS header size %"PRIu32" > packet size %d\n",
1054 header_size, pkt->size);
1055 pes->flags |= AV_PKT_FLAG_CORRUPT;
1056 } else {
1057 pkt->data += header_size;
1058 pkt->size -= header_size;
1059 }
1060 }
1061
1062 memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1063
1064 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
1065 if (pes->sub_st && pes->stream_type == STREAM_TYPE_BLURAY_AUDIO_TRUEHD && pes->extended_stream_id == 0x76)
1066 pkt->stream_index = pes->sub_st->index;
1067 else
1068 pkt->stream_index = pes->st->index;
1069 pkt->pts = pes->pts;
1070 pkt->dts = pes->dts;
1071 /* store position of first TS packet of this PES packet */
1072 pkt->pos = pes->ts_packet_pos;
1073 pkt->flags = pes->flags;
1074
1075 pes->buffer = NULL;
1076 reset_pes_packet_state(pes);
1077
1078 sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
1079 if (!sd)
1080 return AVERROR(ENOMEM);
1081 *sd = pes->stream_id;
1082
1083 return 0;
1084 }
1085
1086 static uint64_t get_ts64(GetBitContext *gb, int bits)
1087 {
1088 if (get_bits_left(gb) < bits)
1089 return AV_NOPTS_VALUE;
1090 return get_bits64(gb, bits);
1091 }
1092
1093 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
1094 const uint8_t *buf, int buf_size)
1095 {
1096 GetBitContext gb;
1097 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
1098 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
1099 int dts_flag = -1, cts_flag = -1;
1100 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
1101 uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
1102 int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
1103
1104 memcpy(buf_padded, buf, buf_padded_size);
1105
1106 init_get_bits(&gb, buf_padded, buf_padded_size * 8);
1107
1108 if (sl->use_au_start)
1109 au_start_flag = get_bits1(&gb);
1110 if (sl->use_au_end)
1111 au_end_flag = get_bits1(&gb);
1112 if (!sl->use_au_start && !sl->use_au_end)
1113 au_start_flag = au_end_flag = 1;
1114 if (sl->ocr_len > 0)
1115 ocr_flag = get_bits1(&gb);
1116 if (sl->use_idle)
1117 idle_flag = get_bits1(&gb);
1118 if (sl->use_padding)
1119 padding_flag = get_bits1(&gb);
1120 if (padding_flag)
1121 padding_bits = get_bits(&gb, 3);
1122
1123 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
1124 if (sl->packet_seq_num_len)
1125 skip_bits_long(&gb, sl->packet_seq_num_len);
1126 if (sl->degr_prior_len)
1127 if (get_bits1(&gb))
1128 skip_bits(&gb, sl->degr_prior_len);
1129 if (ocr_flag)
1130 skip_bits_long(&gb, sl->ocr_len);
1131 if (au_start_flag) {
1132 if (sl->use_rand_acc_pt)
1133 get_bits1(&gb);
1134 if (sl->au_seq_num_len > 0)
1135 skip_bits_long(&gb, sl->au_seq_num_len);
1136 if (sl->use_timestamps) {
1137 dts_flag = get_bits1(&gb);
1138 cts_flag = get_bits1(&gb);
1139 }
1140 }
1141 if (sl->inst_bitrate_len)
1142 inst_bitrate_flag = get_bits1(&gb);
1143 if (dts_flag == 1)
1144 dts = get_ts64(&gb, sl->timestamp_len);
1145 if (cts_flag == 1)
1146 cts = get_ts64(&gb, sl->timestamp_len);
1147 if (sl->au_len > 0)
1148 skip_bits_long(&gb, sl->au_len);
1149 if (inst_bitrate_flag)
1150 skip_bits_long(&gb, sl->inst_bitrate_len);
1151 }
1152
1153 if (dts != AV_NOPTS_VALUE)
1154 pes->dts = dts;
1155 if (cts != AV_NOPTS_VALUE)
1156 pes->pts = cts;
1157
1158 if (sl->timestamp_len && sl->timestamp_res)
1159 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
1160
1161 return (get_bits_count(&gb) + 7) >> 3;
1162 }
1163
1164 static AVBufferRef *buffer_pool_get(MpegTSContext *ts, int size)
1165 {
1166 int index = av_log2(size + AV_INPUT_BUFFER_PADDING_SIZE);
1167 if (!ts->pools[index]) {
1168 int pool_size = FFMIN(ts->max_packet_size + AV_INPUT_BUFFER_PADDING_SIZE, 2 << index);
1169 ts->pools[index] = av_buffer_pool_init(pool_size, NULL);
1170 if (!ts->pools[index])
1171 return NULL;
1172 }
1173 return av_buffer_pool_get(ts->pools[index]);
1174 }
1175
1176 /* return non zero if a packet could be constructed */
1177 static int mpegts_push_data(MpegTSFilter *filter,
1178 const uint8_t *buf, int buf_size, int is_start,
1179 int64_t pos)
1180 {
1181 PESContext *pes = filter->u.pes_filter.opaque;
1182 MpegTSContext *ts = pes->ts;
1183 const uint8_t *p;
1184 int ret, len;
1185
1186 if (!ts->pkt)
1187 return 0;
1188
1189 if (is_start) {
1190 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1191 ret = new_pes_packet(pes, ts->pkt);
1192 if (ret < 0)
1193 return ret;
1194 ts->stop_parse = 1;
1195 } else {
1196 reset_pes_packet_state(pes);
1197 }
1198 pes->state = MPEGTS_HEADER;
1199 pes->ts_packet_pos = pos;
1200 }
1201 p = buf;
1202 while (buf_size > 0) {
1203 switch (pes->state) {
1204 case MPEGTS_HEADER:
1205 len = PES_START_SIZE - pes->data_index;
1206 if (len > buf_size)
1207 len = buf_size;
1208 memcpy(pes->header + pes->data_index, p, len);
1209 pes->data_index += len;
1210 p += len;
1211 buf_size -= len;
1212 if (pes->data_index == PES_START_SIZE) {
1213 /* we got all the PES or section header. We can now
1214 * decide */
1215 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1216 pes->header[2] == 0x01) {
1217 /* it must be an MPEG-2 PES stream */
1218 pes->stream_id = pes->header[3];
1219 av_log(pes->stream, AV_LOG_TRACE, "pid=%x stream_id=%#x\n", pes->pid, pes->stream_id);
1220
1221 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1222 (!pes->sub_st ||
1223 pes->sub_st->discard == AVDISCARD_ALL)) ||
1224 pes->stream_id == STREAM_ID_PADDING_STREAM)
1225 goto skip;
1226
1227 /* stream not present in PMT */
1228 if (!pes->st) {
1229 if (ts->skip_changes)
1230 goto skip;
1231 if (ts->merge_pmt_versions)
1232 goto skip; /* wait for PMT to merge new stream */
1233
1234 pes->st = avformat_new_stream(ts->stream, NULL);
1235 if (!pes->st)
1236 return AVERROR(ENOMEM);
1237 pes->st->id = pes->pid;
1238 mpegts_set_stream_info(pes->st, pes, 0, 0);
1239 }
1240
1241 pes->PES_packet_length = AV_RB16(pes->header + 4);
1242 /* NOTE: zero length means the PES size is unbounded */
1243
1244 if (pes->stream_id != STREAM_ID_PROGRAM_STREAM_MAP &&
1245 pes->stream_id != STREAM_ID_PRIVATE_STREAM_2 &&
1246 pes->stream_id != STREAM_ID_ECM_STREAM &&
1247 pes->stream_id != STREAM_ID_EMM_STREAM &&
1248 pes->stream_id != STREAM_ID_PROGRAM_STREAM_DIRECTORY &&
1249 pes->stream_id != STREAM_ID_DSMCC_STREAM &&
1250 pes->stream_id != STREAM_ID_TYPE_E_STREAM) {
1251 FFStream *const pes_sti = ffstream(pes->st);
1252 pes->state = MPEGTS_PESHEADER;
1253 if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes_sti->request_probe) {
1254 av_log(pes->stream, AV_LOG_TRACE,
1255 "pid=%x stream_type=%x probing\n",
1256 pes->pid,
1257 pes->stream_type);
1258 pes_sti->request_probe = 1;
1259 }
1260 } else {
1261 pes->pes_header_size = 6;
1262 pes->state = MPEGTS_PAYLOAD;
1263 pes->data_index = 0;
1264 }
1265 } else {
1266 /* otherwise, it should be a table */
1267 /* skip packet */
1268 skip:
1269 pes->state = MPEGTS_SKIP;
1270 continue;
1271 }
1272 }
1273 break;
1274 /**********************************************/
1275 /* PES packing parsing */
1276 case MPEGTS_PESHEADER:
1277 len = PES_HEADER_SIZE - pes->data_index;
1278 if (len < 0)
1279 return AVERROR_INVALIDDATA;
1280 if (len > buf_size)
1281 len = buf_size;
1282 memcpy(pes->header + pes->data_index, p, len);
1283 pes->data_index += len;
1284 p += len;
1285 buf_size -= len;
1286 if (pes->data_index == PES_HEADER_SIZE) {
1287 pes->pes_header_size = pes->header[8] + 9;
1288 pes->state = MPEGTS_PESHEADER_FILL;
1289 }
1290 break;
1291 case MPEGTS_PESHEADER_FILL:
1292 len = pes->pes_header_size - pes->data_index;
1293 if (len < 0)
1294 return AVERROR_INVALIDDATA;
1295 if (len > buf_size)
1296 len = buf_size;
1297 memcpy(pes->header + pes->data_index, p, len);
1298 pes->data_index += len;
1299 p += len;
1300 buf_size -= len;
1301 if (pes->data_index == pes->pes_header_size) {
1302 const uint8_t *r;
1303 unsigned int flags, pes_ext, skip;
1304
1305 flags = pes->header[7];
1306 r = pes->header + 9;
1307 pes->pts = AV_NOPTS_VALUE;
1308 pes->dts = AV_NOPTS_VALUE;
1309 if ((flags & 0xc0) == 0x80) {
1310 pes->dts = pes->pts = ff_parse_pes_pts(r);
1311 r += 5;
1312 } else if ((flags & 0xc0) == 0xc0) {
1313 pes->pts = ff_parse_pes_pts(r);
1314 r += 5;
1315 pes->dts = ff_parse_pes_pts(r);
1316 r += 5;
1317 }
1318 pes->extended_stream_id = -1;
1319 if (flags & 0x01) { /* PES extension */
1320 pes_ext = *r++;
1321 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1322 skip = (pes_ext >> 4) & 0xb;
1323 skip += skip & 0x9;
1324 r += skip;
1325 if ((pes_ext & 0x41) == 0x01 &&
1326 (r + 2) <= (pes->header + pes->pes_header_size)) {
1327 /* PES extension 2 */
1328 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1329 pes->extended_stream_id = r[1];
1330 }
1331 }
1332
1333 /* we got the full header. We parse it and get the payload */
1334 pes->state = MPEGTS_PAYLOAD;
1335 pes->data_index = 0;
1336 if (pes->stream_type == STREAM_TYPE_ISO_IEC_14496_PES && buf_size > 0) {
1337 int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1338 buf_size);
1339 pes->pes_header_size += sl_header_bytes;
1340 p += sl_header_bytes;
1341 buf_size -= sl_header_bytes;
1342 }
1343 if (pes->stream_type == STREAM_TYPE_METADATA &&
1344 pes->stream_id == STREAM_ID_METADATA_STREAM &&
1345 pes->st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV &&
1346 buf_size >= 5) {
1347 /* skip metadata access unit header - see MISB ST 1402 */
1348 pes->pes_header_size += 5;
1349 p += 5;
1350 buf_size -= 5;
1351 }
1352 if ( pes->ts->fix_teletext_pts
1353 && ( pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
1354 || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1355 ) {
1356 AVProgram *p = NULL;
1357 int pcr_found = 0;
1358 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1359 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1360 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1361 if (f) {
1362 AVStream *st = NULL;
1363 if (f->type == MPEGTS_PES) {
1364 PESContext *pcrpes = f->u.pes_filter.opaque;
1365 if (pcrpes)
1366 st = pcrpes->st;
1367 } else if (f->type == MPEGTS_PCR) {
1368 int i;
1369 for (i = 0; i < p->nb_stream_indexes; i++) {
1370 AVStream *pst = pes->stream->streams[p->stream_index[i]];
1371 if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1372 st = pst;
1373 }
1374 }
1375 if (f->last_pcr != -1 && !f->discard) {
1376 // teletext packets do not always have correct timestamps,
1377 // the standard says they should be handled after 40.6 ms at most,
1378 // and the pcr error to this packet should be no more than 100 ms.
1379 // TODO: we should interpolate the PCR, not just use the last one
1380 int64_t pcr = f->last_pcr / SYSTEM_CLOCK_FREQUENCY_DIVISOR;
1381 pcr_found = 1;
1382 if (st) {
1383 const FFStream *const sti = ffstream(st);
1384 FFStream *const pes_sti = ffstream(pes->st);
1385
1386 pes_sti->pts_wrap_reference = sti->pts_wrap_reference;
1387 pes_sti->pts_wrap_behavior = sti->pts_wrap_behavior;
1388 }
1389 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1390 pes->pts = pes->dts = pcr;
1391 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1392 pes->dts > pcr + 3654 + 9000) {
1393 pes->pts = pes->dts = pcr + 3654 + 9000;
1394 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1395 pes->dts > pcr + 10*90000) { //10sec
1396 pes->pts = pes->dts = pcr + 3654 + 9000;
1397 }
1398 break;
1399 }
1400 }
1401 }
1402 }
1403
1404 if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1405 !pcr_found) {
1406 av_log(pes->stream, AV_LOG_VERBOSE,
1407 "Forcing DTS/PTS to be unset for a "
1408 "non-trustworthy PES packet for PID %d as "
1409 "PCR hasn't been received yet.\n",
1410 pes->pid);
1411 pes->dts = pes->pts = AV_NOPTS_VALUE;
1412 }
1413 }
1414 }
1415 break;
1416 case MPEGTS_PAYLOAD:
1417 do {
1418 int max_packet_size = ts->max_packet_size;
1419 if (pes->PES_packet_length && pes->PES_packet_length + PES_START_SIZE > pes->pes_header_size)
1420 max_packet_size = pes->PES_packet_length + PES_START_SIZE - pes->pes_header_size;
1421
1422 if (pes->data_index > 0 &&
1423 pes->data_index + buf_size > max_packet_size) {
1424 ret = new_pes_packet(pes, ts->pkt);
1425 if (ret < 0)
1426 return ret;
1427 pes->PES_packet_length = 0;
1428 max_packet_size = ts->max_packet_size;
1429 ts->stop_parse = 1;
1430 } else if (pes->data_index == 0 &&
1431 buf_size > max_packet_size) {
1432 // pes packet size is < ts size packet and pes data is padded with STUFFING_BYTE
1433 // not sure if this is legal in ts but see issue #2392
1434 buf_size = max_packet_size;
1435 }
1436
1437 if (!pes->buffer) {
1438 pes->buffer = buffer_pool_get(ts, max_packet_size);
1439 if (!pes->buffer)
1440 return AVERROR(ENOMEM);
1441 }
1442
1443 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1444 pes->data_index += buf_size;
1445 /* emit complete packets with known packet size
1446 * decreases demuxer delay for infrequent packets like subtitles from
1447 * a couple of seconds to milliseconds for properly muxed files. */
1448 if (!ts->stop_parse && pes->PES_packet_length &&
1449 pes->pes_header_size + pes->data_index == pes->PES_packet_length + PES_START_SIZE) {
1450 ts->stop_parse = 1;
1451 ret = new_pes_packet(pes, ts->pkt);
1452 pes->state = MPEGTS_SKIP;
1453 if (ret < 0)
1454 return ret;
1455 }
1456 } while (0);
1457 buf_size = 0;
1458 break;
1459 case MPEGTS_SKIP:
1460 buf_size = 0;
1461 break;
1462 }
1463 }
1464
1465 return 0;
1466 }
1467
1468 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1469 {
1470 MpegTSFilter *tss;
1471 PESContext *pes;
1472
1473 /* if no pid found, then add a pid context */
1474 pes = av_mallocz(sizeof(PESContext));
1475 if (!pes)
1476 return 0;
1477 pes->ts = ts;
1478 pes->stream = ts->stream;
1479 pes->pid = pid;
1480 pes->pcr_pid = pcr_pid;
1481 pes->state = MPEGTS_SKIP;
1482 pes->pts = AV_NOPTS_VALUE;
1483 pes->dts = AV_NOPTS_VALUE;
1484 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1485 if (!tss) {
1486 av_free(pes);
1487 return 0;
1488 }
1489 return pes;
1490 }
1491
1492 #define MAX_LEVEL 4
1493 typedef struct MP4DescrParseContext {
1494 AVFormatContext *s;
1495 FFIOContext pb;
1496 Mp4Descr *descr;
1497 Mp4Descr *active_descr;
1498 int descr_count;
1499 int max_descr_count;
1500 int level;
1501 int predefined_SLConfigDescriptor_seen;
1502 } MP4DescrParseContext;
1503
1504 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1505 const uint8_t *buf, unsigned size,
1506 Mp4Descr *descr, int max_descr_count)
1507 {
1508 if (size > (1 << 30))
1509 return AVERROR_INVALIDDATA;
1510
1511 ffio_init_read_context(&d->pb, buf, size);
1512
1513 d->s = s;
1514 d->level = 0;
1515 d->descr_count = 0;
1516 d->descr = descr;
1517 d->active_descr = NULL;
1518 d->max_descr_count = max_descr_count;
1519
1520 return 0;
1521 }
1522
1523 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1524 {
1525 int64_t new_off = avio_tell(pb);
1526 (*len) -= new_off - *off;
1527 *off = new_off;
1528 }
1529
1530 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1531 int target_tag);
1532
1533 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1534 {
1535 while (len > 0) {
1536 int ret = parse_mp4_descr(d, off, len, 0);
1537 if (ret < 0)
1538 return ret;
1539 update_offsets(&d->pb.pub, &off, &len);
1540 }
1541 return 0;
1542 }
1543
1544 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1545 {
1546 AVIOContext *const pb = &d->pb.pub;
1547 avio_rb16(pb); // ID
1548 avio_r8(pb);
1549 avio_r8(pb);
1550 avio_r8(pb);
1551 avio_r8(pb);
1552 avio_r8(pb);
1553 update_offsets(pb, &off, &len);
1554 return parse_mp4_descr_arr(d, off, len);
1555 }
1556
1557 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1558 {
1559 int id_flags;
1560 if (len < 2)
1561 return 0;
1562 id_flags = avio_rb16(&d->pb.pub);
1563 if (!(id_flags & 0x0020)) { // URL_Flag
1564 update_offsets(&d->pb.pub, &off, &len);
1565 return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1566 } else {
1567 return 0;
1568 }
1569 }
1570
1571 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1572 {
1573 AVIOContext *const pb = &d->pb.pub;
1574 int es_id = 0;
1575 int ret = 0;
1576
1577 if (d->descr_count >= d->max_descr_count)
1578 return AVERROR_INVALIDDATA;
1579 ff_mp4_parse_es_descr(pb, &es_id);
1580 d->active_descr = d->descr + (d->descr_count++);
1581
1582 d->active_descr->es_id = es_id;
1583 update_offsets(pb, &off, &len);
1584 if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
1585 return ret;
1586 update_offsets(pb, &off, &len);
1587 if (len > 0)
1588 ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1589 d->active_descr = NULL;
1590 return ret;
1591 }
1592
1593 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1594 int len)
1595 {
1596 Mp4Descr *descr = d->active_descr;
1597 if (!descr)
1598 return AVERROR_INVALIDDATA;
1599 d->active_descr->dec_config_descr = av_malloc(len);
1600 if (!descr->dec_config_descr)
1601 return AVERROR(ENOMEM);
1602 descr->dec_config_descr_len = len;
1603 avio_read(&d->pb.pub, descr->dec_config_descr, len);
1604 return 0;
1605 }
1606
1607 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1608 {
1609 Mp4Descr *descr = d->active_descr;
1610 AVIOContext *const pb = &d->pb.pub;
1611 int predefined;
1612 if (!descr)
1613 return AVERROR_INVALIDDATA;
1614
1615 #define R8_CHECK_CLIP_MAX(dst, maxv) do { \
1616 descr->sl.dst = avio_r8(pb); \
1617 if (descr->sl.dst > maxv) { \
1618 descr->sl.dst = maxv; \
1619 return AVERROR_INVALIDDATA; \
1620 } \
1621 } while (0)
1622
1623 predefined = avio_r8(pb);
1624 if (!predefined) {
1625 int lengths;
1626 int flags = avio_r8(pb);
1627 descr->sl.use_au_start = !!(flags & 0x80);
1628 descr->sl.use_au_end = !!(flags & 0x40);
1629 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1630 descr->sl.use_padding = !!(flags & 0x08);
1631 descr->sl.use_timestamps = !!(flags & 0x04);
1632 descr->sl.use_idle = !!(flags & 0x02);
1633 descr->sl.timestamp_res = avio_rb32(pb);
1634 avio_rb32(pb);
1635 R8_CHECK_CLIP_MAX(timestamp_len, 63);
1636 R8_CHECK_CLIP_MAX(ocr_len, 63);
1637 R8_CHECK_CLIP_MAX(au_len, 31);
1638 descr->sl.inst_bitrate_len = avio_r8(pb);
1639 lengths = avio_rb16(pb);
1640 descr->sl.degr_prior_len = lengths >> 12;
1641 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1642 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1643 } else if (!d->predefined_SLConfigDescriptor_seen){
1644 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1645 d->predefined_SLConfigDescriptor_seen = 1;
1646 }
1647 return 0;
1648 }
1649
1650 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1651 int target_tag)
1652 {
1653 int tag;
1654 AVIOContext *const pb = &d->pb.pub;
1655 int len1 = ff_mp4_read_descr(d->s, pb, &tag);
1656 int ret = 0;
1657
1658 update_offsets(pb, &off, &len);
1659 if (len < 0 || len1 > len || len1 <= 0) {
1660 av_log(d->s, AV_LOG_ERROR,
1661 "Tag %x length violation new length %d bytes remaining %d\n",
1662 tag, len1, len);
1663 return AVERROR_INVALIDDATA;
1664 }
1665
1666 if (d->level++ >= MAX_LEVEL) {
1667 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1668 ret = AVERROR_INVALIDDATA;
1669 goto done;
1670 }
1671
1672 if (target_tag && tag != target_tag) {
1673 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1674 target_tag);
1675 ret = AVERROR_INVALIDDATA;
1676 goto done;
1677 }
1678
1679 switch (tag) {
1680 case MP4IODescrTag:
1681 ret = parse_MP4IODescrTag(d, off, len1);
1682 break;
1683 case MP4ODescrTag:
1684 ret = parse_MP4ODescrTag(d, off, len1);
1685 break;
1686 case MP4ESDescrTag:
1687 ret = parse_MP4ESDescrTag(d, off, len1);
1688 break;
1689 case MP4DecConfigDescrTag:
1690 ret = parse_MP4DecConfigDescrTag(d, off, len1);
1691 break;
1692 case MP4SLDescrTag:
1693 ret = parse_MP4SLDescrTag(d, off, len1);
1694 break;
1695 }
1696
1697
1698 done:
1699 d->level--;
1700 avio_seek(pb, off + len1, SEEK_SET);
1701 return ret;
1702 }
1703
1704 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1705 Mp4Descr *descr, int *descr_count, int max_descr_count)
1706 {
1707 MP4DescrParseContext d;
1708 int ret;
1709
1710 d.predefined_SLConfigDescriptor_seen = 0;
1711
1712 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1713 if (ret < 0)
1714 return ret;
1715
1716 ret = parse_mp4_descr(&d, avio_tell(&d.pb.pub), size, MP4IODescrTag);
1717
1718 *descr_count += d.descr_count;
1719 return ret;
1720 }
1721
1722 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1723 Mp4Descr *descr, int *descr_count, int max_descr_count)
1724 {
1725 MP4DescrParseContext d;
1726 int ret;
1727
1728 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1729 if (ret < 0)
1730 return ret;
1731
1732 ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb.pub), size);
1733
1734 *descr_count = d.descr_count;
1735 return ret;
1736 }
1737
1738 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1739 int section_len)
1740 {
1741 MpegTSContext *ts = filter->u.section_filter.opaque;
1742 MpegTSSectionFilter *tssf = &filter->u.section_filter;
1743 SectionHeader h;
1744 const uint8_t *p, *p_end;
1745 int mp4_descr_count = 0;
1746 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1747 int i, pid;
1748 AVFormatContext *s = ts->stream;
1749
1750 p_end = section + section_len - 4;
1751 p = section;
1752 if (parse_section_header(&h, &p, p_end) < 0)
1753 return;
1754 if (h.tid != M4OD_TID)
1755 return;
1756 if (skip_identical(&h, tssf))
1757 return;
1758
1759 mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1760 MAX_MP4_DESCR_COUNT);
1761
1762 for (pid = 0; pid < NB_PID_MAX; pid++) {
1763 if (!ts->pids[pid])
1764 continue;
1765 for (i = 0; i < mp4_descr_count; i++) {
1766 PESContext *pes;
1767 AVStream *st;
1768 FFStream *sti;
1769 FFIOContext pb;
1770 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1771 continue;
1772 if (ts->pids[pid]->type != MPEGTS_PES) {
1773 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1774 continue;
1775 }
1776 pes = ts->pids[pid]->u.pes_filter.opaque;
1777 st = pes->st;
1778 if (!st)
1779 continue;
1780 sti = ffstream(st);
1781
1782 pes->sl = mp4_descr[i].sl;
1783
1784 ffio_init_read_context(&pb, mp4_descr[i].dec_config_descr,
1785 mp4_descr[i].dec_config_descr_len);
1786 ff_mp4_read_dec_config_descr(s, st, &pb.pub);
1787 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1788 st->codecpar->extradata_size > 0)
1789 sti->need_parsing = 0;
1790 if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
1791 st->codecpar->extradata_size > 0)
1792 sti->need_parsing = 0;
1793
1794 st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
1795 sti->need_context_update = 1;
1796 }
1797 }
1798 for (i = 0; i < mp4_descr_count; i++)
1799 av_free(mp4_descr[i].dec_config_descr);
1800 }
1801
1802 static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
1803 int section_len)
1804 {
1805 AVProgram *prg = NULL;
1806 MpegTSContext *ts = filter->u.section_filter.opaque;
1807
1808 int idx = ff_find_stream_index(ts->stream, filter->pid);
1809 if (idx < 0)
1810 return;
1811
1812 /**
1813 * In case we receive an SCTE-35 packet before mpegts context is fully
1814 * initialized.
1815 */
1816 if (!ts->pkt)
1817 return;
1818
1819 new_data_packet(section, section_len, ts->pkt);
1820 ts->pkt->stream_index = idx;
1821 prg = av_find_program_from_stream(ts->stream, NULL, idx);
1822 if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
1823 MpegTSFilter *f = ts->pids[prg->pcr_pid];
1824 if (f && f->last_pcr != -1)
1825 ts->pkt->pts = ts->pkt->dts = f->last_pcr/SYSTEM_CLOCK_FREQUENCY_DIVISOR;
1826 }
1827 ts->stop_parse = 1;
1828
1829 }
1830
1831 static const uint8_t opus_coupled_stream_cnt[9] = {
1832 1, 0, 1, 1, 2, 2, 2, 3, 3
1833 };
1834
1835 static const uint8_t opus_stream_cnt[9] = {
1836 1, 1, 1, 2, 2, 3, 4, 4, 5,
1837 };
1838
1839 static const uint8_t opus_channel_map[8][8] = {
1840 { 0 },
1841 { 0,1 },
1842 { 0,2,1 },
1843 { 0,1,2,3 },
1844 { 0,4,1,2,3 },
1845 { 0,4,1,2,3,5 },
1846 { 0,4,1,2,3,5,6 },
1847 { 0,6,1,2,3,4,5,7 },
1848 };
1849
1850 static int parse_mpeg2_extension_descriptor(AVFormatContext *fc, AVStream *st, int prg_id,
1851 const uint8_t **pp, const uint8_t *desc_end)
1852 {
1853 MpegTSContext *ts = fc->priv_data;
1854 int ext_tag = get8(pp, desc_end);
1855
1856 switch (ext_tag) {
1857 case JXS_VIDEO_DESCRIPTOR: /* JPEG-XS video descriptor*/
1858 {
1859 int horizontal_size, vertical_size, schar;
1860 int colour_primaries, transfer_characteristics, matrix_coefficients, video_full_range_flag;
1861 int descriptor_version, interlace_mode, n_fields;
1862 unsigned frat;
1863
1864 if (desc_end - *pp < 29)
1865 return AVERROR_INVALIDDATA;
1866
1867 descriptor_version = get8(pp, desc_end);
1868 if (descriptor_version) {
1869 av_log(fc, AV_LOG_WARNING, "Unsupported JPEG-XS descriptor version (%d != 0)", descriptor_version);
1870 return AVERROR_INVALIDDATA;
1871 }
1872
1873 horizontal_size = get16(pp, desc_end);
1874 vertical_size = get16(pp, desc_end);
1875 *pp += 4; /* brat */
1876 frat = bytestream_get_be32(pp);
1877 schar = get16(pp, desc_end);
1878 *pp += 2; /* Ppih */
1879 *pp += 2; /* Plev */
1880 *pp += 4; /* max_buffer_size */
1881 *pp += 1; /* buffer_model_type */
1882 colour_primaries = get8(pp, desc_end);
1883 transfer_characteristics = get8(pp, desc_end);
1884 matrix_coefficients = get8(pp, desc_end);
1885 video_full_range_flag = (get8(pp, desc_end) & 0x80) == 0x80 ? 1 : 0;
1886
1887 interlace_mode = (frat >> 30) & 0x3;
1888 if (interlace_mode == 3) {
1889 av_log(fc, AV_LOG_WARNING, "Unknown JPEG XS interlace mode 3");
1890 return AVERROR_INVALIDDATA;
1891 }
1892
1893 st->codecpar->field_order = interlace_mode == 0 ? AV_FIELD_PROGRESSIVE
1894 : (interlace_mode == 1 ? AV_FIELD_TT : AV_FIELD_BB);
1895 n_fields = st->codecpar->field_order == AV_FIELD_PROGRESSIVE ? 1 : 2;
1896
1897 st->codecpar->width = horizontal_size;
1898 st->codecpar->height = vertical_size * n_fields;
1899
1900 if (frat != 0) {
1901 int framerate_num = (frat & 0x0000FFFFU);
1902 int framerate_den = ((frat >> 24) & 0x0000003FU);
1903
1904 if (framerate_den == 2) {
1905 framerate_num *= 1000;
1906 framerate_den = 1001;
1907 } else if (framerate_den != 1) {
1908 av_log(fc, AV_LOG_WARNING, "Unknown JPEG XS framerate denominator code %u", framerate_den);
1909 return AVERROR_INVALIDDATA;
1910 }
1911
1912 st->codecpar->framerate.num = framerate_num;
1913 st->codecpar->framerate.den = framerate_den;
1914 }
1915
1916 switch (schar & 0xf) {
1917 case 0: st->codecpar->format = AV_PIX_FMT_YUV422P10LE; break;
1918 case 1: st->codecpar->format = AV_PIX_FMT_YUV444P10LE; break;
1919 default:
1920 av_log(fc, AV_LOG_WARNING, "Unknown JPEG XS sampling format");
1921 break;
1922 }
1923
1924 st->codecpar->color_range = video_full_range_flag ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
1925 st->codecpar->color_primaries = colour_primaries;
1926 st->codecpar->color_trc = transfer_characteristics;
1927 st->codecpar->color_space = matrix_coefficients;
1928 }
1929 break;
1930 case LCEVC_VIDEO_DESCRIPTOR:
1931 {
1932 struct Program *p = get_program(ts, prg_id);
1933 struct StreamGroup *stg;
1934 int lcevc_stream_tag = get8(pp, desc_end);
1935 int i;
1936
1937 if (!p)
1938 return 0;
1939
1940 if (st->codecpar->codec_id != AV_CODEC_ID_LCEVC)
1941 return AVERROR_INVALIDDATA;
1942
1943 for (i = 0; i < p->nb_stream_groups; i++) {
1944 stg = &p->stream_groups[i];
1945 if (stg->type != AV_STREAM_GROUP_PARAMS_LCEVC)
1946 continue;
1947 if (stg->id == lcevc_stream_tag)
1948 break;
1949 }
1950 if (i == p->nb_stream_groups) {
1951 if (p->nb_stream_groups == MAX_STREAMS_PER_PROGRAM)
1952 return AVERROR(EINVAL);
1953 p->nb_stream_groups++;
1954 }
1955
1956 stg = &p->stream_groups[i];
1957 stg->id = lcevc_stream_tag;
1958 stg->type = AV_STREAM_GROUP_PARAMS_LCEVC;
1959 for (i = 0; i < stg->nb_streams; i++) {
1960 if (stg->streams[i]->codecpar->codec_id == AV_CODEC_ID_LCEVC)
1961 break;
1962 }
1963 if (i == stg->nb_streams) {
1964 if (stg->nb_streams == MAX_STREAMS_PER_PROGRAM)
1965 return AVERROR(EINVAL);
1966 stg->streams[stg->nb_streams++] = st;
1967 } else
1968 stg->streams[i] = st;
1969
1970 av_assert0(i < stg->nb_streams);
1971 }
1972 break;
1973 case LCEVC_LINKAGE_DESCRIPTOR:
1974 {
1975 struct Program *p = get_program(ts, prg_id);
1976 int num_lcevc_stream_tags = get8(pp, desc_end);
1977
1978 if (!p)
1979 return 0;
1980
1981 if (st->codecpar->codec_id == AV_CODEC_ID_LCEVC)
1982 return AVERROR_INVALIDDATA;
1983
1984 for (int i = 0; i < num_lcevc_stream_tags; i++) {
1985 struct StreamGroup *stg = NULL;
1986 int lcevc_stream_tag = get8(pp, desc_end);;
1987 int j;
1988
1989 for (j = 0; j < p->nb_stream_groups; j++) {
1990 stg = &p->stream_groups[j];
1991 if (stg->type != AV_STREAM_GROUP_PARAMS_LCEVC)
1992 continue;
1993 if (stg->id == lcevc_stream_tag)
1994 break;
1995 }
1996 if (j == p->nb_stream_groups) {
1997 if (p->nb_stream_groups == MAX_STREAMS_PER_PROGRAM)
1998 return AVERROR(EINVAL);
1999 p->nb_stream_groups++;
2000 }
2001
2002 stg = &p->stream_groups[j];
2003 stg->id = lcevc_stream_tag;
2004 stg->type = AV_STREAM_GROUP_PARAMS_LCEVC;
2005 for (j = 0; j < stg->nb_streams; j++) {
2006 if (stg->streams[j]->index == st->index)
2007 break;
2008 }
2009 if (j == stg->nb_streams) {
2010 if (stg->nb_streams == MAX_STREAMS_PER_PROGRAM)
2011 return AVERROR(EINVAL);
2012 stg->streams[stg->nb_streams++] = st;
2013 }
2014 }
2015 }
2016 break;
2017 default:
2018 break;
2019 }
2020
2021 return 0;
2022 }
2023
2024 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type, int prg_id,
2025 const uint8_t **pp, const uint8_t *desc_list_end,
2026 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
2027 MpegTSContext *ts)
2028 {
2029 FFStream *const sti = ffstream(st);
2030 const uint8_t *desc_end;
2031 int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
2032 char language[252];
2033 int i;
2034
2035 desc_tag = get8(pp, desc_list_end);
2036 if (desc_tag < 0)
2037 return AVERROR_INVALIDDATA;
2038 desc_len = get8(pp, desc_list_end);
2039 if (desc_len < 0)
2040 return AVERROR_INVALIDDATA;
2041 desc_end = *pp + desc_len;
2042 if (desc_end > desc_list_end)
2043 return AVERROR_INVALIDDATA;
2044
2045 av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
2046
2047 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || sti->request_probe > 0) &&
2048 stream_type == STREAM_TYPE_PRIVATE_DATA)
2049 mpegts_find_stream_type(st, desc_tag, DESC_types);
2050
2051 switch (desc_tag) {
2052 case VIDEO_STREAM_DESCRIPTOR:
2053 if (get8(pp, desc_end) & 0x1) {
2054 st->disposition |= AV_DISPOSITION_STILL_IMAGE;
2055 }
2056 break;
2057 case SL_DESCRIPTOR:
2058 desc_es_id = get16(pp, desc_end);
2059 if (desc_es_id < 0)
2060 break;
2061 if (ts && ts->pids[pid])
2062 ts->pids[pid]->es_id = desc_es_id;
2063 for (i = 0; i < mp4_descr_count; i++)
2064 if (mp4_descr[i].dec_config_descr_len &&
2065 mp4_descr[i].es_id == desc_es_id) {
2066 FFIOContext pb;
2067 ffio_init_read_context(&pb, mp4_descr[i].dec_config_descr,
2068 mp4_descr[i].dec_config_descr_len);
2069 ff_mp4_read_dec_config_descr(fc, st, &pb.pub);
2070 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
2071 st->codecpar->extradata_size > 0) {
2072 sti->need_parsing = 0;
2073 sti->need_context_update = 1;
2074 }
2075 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
2076 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
2077 }
2078 break;
2079 case FMC_DESCRIPTOR:
2080 if (get16(pp, desc_end) < 0)
2081 break;
2082 if (mp4_descr_count > 0 &&
2083 (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
2084 (sti->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
2085 sti->request_probe > 0) &&
2086 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
2087 FFIOContext pb;
2088 ffio_init_read_context(&pb, mp4_descr->dec_config_descr,
2089 mp4_descr->dec_config_descr_len);
2090 ff_mp4_read_dec_config_descr(fc, st, &pb.pub);
2091 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
2092 st->codecpar->extradata_size > 0) {
2093 sti->request_probe = sti->need_parsing = 0;
2094 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2095 sti->need_context_update = 1;
2096 }
2097 }
2098 break;
2099 case TELETEXT_DESCRIPTOR:
2100 {
2101 uint8_t *extradata = NULL;
2102 int language_count = desc_len / 5, ret;
2103
2104 if (desc_len > 0 && desc_len % 5 != 0)
2105 return AVERROR_INVALIDDATA;
2106
2107 if (language_count > 0) {
2108 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
2109 av_assert0(language_count <= sizeof(language) / 4);
2110
2111 if (st->codecpar->extradata == NULL) {
2112 ret = ff_alloc_extradata(st->codecpar, language_count * 2);
2113 if (ret < 0)
2114 return ret;
2115 }
2116
2117 if (st->codecpar->extradata_size < language_count * 2)
2118 return AVERROR_INVALIDDATA;
2119
2120 extradata = st->codecpar->extradata;
2121
2122 for (i = 0; i < language_count; i++) {
2123 language[i * 4 + 0] = get8(pp, desc_end);
2124 language[i * 4 + 1] = get8(pp, desc_end);
2125 language[i * 4 + 2] = get8(pp, desc_end);
2126 language[i * 4 + 3] = ',';
2127
2128 memcpy(extradata, *pp, 2);
2129 extradata += 2;
2130
2131 *pp += 2;
2132 }
2133
2134 language[i * 4 - 1] = 0;
2135 av_dict_set(&st->metadata, "language", language, 0);
2136 sti->need_context_update = 1;
2137 }
2138 }
2139 break;
2140 case SUBTITLING_DESCRIPTOR:
2141 {
2142 /* 8 bytes per DVB subtitle substream data:
2143 * ISO_639_language_code (3 bytes),
2144 * subtitling_type (1 byte),
2145 * composition_page_id (2 bytes),
2146 * ancillary_page_id (2 bytes) */
2147 int language_count = desc_len / 8, ret;
2148
2149 if (desc_len > 0 && desc_len % 8 != 0)
2150 return AVERROR_INVALIDDATA;
2151
2152 if (language_count > 1) {
2153 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
2154 }
2155
2156 if (language_count > 0) {
2157 uint8_t *extradata;
2158
2159 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
2160 av_assert0(language_count <= sizeof(language) / 4);
2161
2162 if (st->codecpar->extradata == NULL) {
2163 ret = ff_alloc_extradata(st->codecpar, language_count * 5);
2164 if (ret < 0)
2165 return ret;
2166 }
2167
2168 if (st->codecpar->extradata_size < language_count * 5)
2169 return AVERROR_INVALIDDATA;
2170
2171 extradata = st->codecpar->extradata;
2172
2173 for (i = 0; i < language_count; i++) {
2174 language[i * 4 + 0] = get8(pp, desc_end);
2175 language[i * 4 + 1] = get8(pp, desc_end);
2176 language[i * 4 + 2] = get8(pp, desc_end);
2177 language[i * 4 + 3] = ',';
2178
2179 /* hearing impaired subtitles detection using subtitling_type */
2180 switch (*pp[0]) {
2181 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
2182 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
2183 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
2184 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
2185 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
2186 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
2187 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2188 break;
2189 }
2190
2191 extradata[4] = get8(pp, desc_end); /* subtitling_type */
2192 memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
2193 extradata += 5;
2194
2195 *pp += 4;
2196 }
2197
2198 language[i * 4 - 1] = 0;
2199 av_dict_set(&st->metadata, "language", language, 0);
2200 sti->need_context_update = 1;
2201 }
2202 }
2203 break;
2204 case ISO_639_LANGUAGE_DESCRIPTOR:
2205 for (i = 0; i + 4 <= desc_len; i += 4) {
2206 language[i + 0] = get8(pp, desc_end);
2207 language[i + 1] = get8(pp, desc_end);
2208 language[i + 2] = get8(pp, desc_end);
2209 language[i + 3] = ',';
2210 switch (get8(pp, desc_end)) {
2211 case 0x01:
2212 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
2213 break;
2214 case 0x02:
2215 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2216 break;
2217 case 0x03:
2218 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2219 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2220 break;
2221 }
2222 }
2223 if (i && language[0]) {
2224 language[i - 1] = 0;
2225 /* don't overwrite language, as it may already have been set by
2226 * another, more specific descriptor (e.g. supplementary audio) */
2227 av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
2228 }
2229 break;
2230 case REGISTRATION_DESCRIPTOR:
2231 st->codecpar->codec_tag = bytestream_get_le32(pp);
2232 av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
2233 if (st->codecpar->codec_id == AV_CODEC_ID_NONE || sti->request_probe > 0) {
2234 mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
2235 if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
2236 sti->request_probe = 50;
2237 }
2238 break;
2239 case STREAM_IDENTIFIER_DESCRIPTOR:
2240 sti->stream_identifier = 1 + get8(pp, desc_end);
2241 break;
2242 case METADATA_DESCRIPTOR:
2243 if (get16(pp, desc_end) == 0xFFFF)
2244 *pp += 4;
2245 if (get8(pp, desc_end) == 0xFF) {
2246 st->codecpar->codec_tag = bytestream_get_le32(pp);
2247 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2248 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
2249 }
2250 break;
2251 case DVB_EXTENSION_DESCRIPTOR: /* DVB extension descriptor */
2252 ext_desc_tag = get8(pp, desc_end);
2253 if (ext_desc_tag < 0)
2254 return AVERROR_INVALIDDATA;
2255 if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
2256 ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
2257 if (!st->codecpar->extradata) {
2258 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
2259 AV_INPUT_BUFFER_PADDING_SIZE);
2260 if (!st->codecpar->extradata)
2261 return AVERROR(ENOMEM);
2262
2263 st->codecpar->extradata_size = sizeof(opus_default_extradata);
2264 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
2265
2266 channel_config_code = get8(pp, desc_end);
2267 if (channel_config_code < 0)
2268 return AVERROR_INVALIDDATA;
2269 if (channel_config_code <= 0x8) {
2270 st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
2271 AV_WL32(&st->codecpar->extradata[12], 48000);
2272 st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
2273 st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
2274 st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
2275 memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
2276 st->codecpar->extradata_size = st->codecpar->extradata[18] ? 21 + channels : 19;
2277 } else {
2278 avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
2279 }
2280 sti->need_parsing = AVSTREAM_PARSE_FULL;
2281 sti->need_context_update = 1;
2282 }
2283 break;
2284 }
2285 if (ext_desc_tag == SUPPLEMENTARY_AUDIO_DESCRIPTOR) {
2286 int flags;
2287
2288 if (desc_len < 1)
2289 return AVERROR_INVALIDDATA;
2290 flags = get8(pp, desc_end);
2291
2292 if ((flags & 0x80) == 0) /* mix_type */
2293 st->disposition |= AV_DISPOSITION_DEPENDENT;
2294
2295 switch ((flags >> 2) & 0x1F) { /* editorial_classification */
2296 case 0x01:
2297 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2298 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2299 break;
2300 case 0x02:
2301 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2302 break;
2303 case 0x03:
2304 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2305 break;
2306 }
2307
2308 if (flags & 0x01) { /* language_code_present */
2309 if (desc_len < 4)
2310 return AVERROR_INVALIDDATA;
2311 language[0] = get8(pp, desc_end);
2312 language[1] = get8(pp, desc_end);
2313 language[2] = get8(pp, desc_end);
2314 language[3] = 0;
2315
2316 /* This language always has to override a possible
2317 * ISO 639 language descriptor language */
2318 if (language[0])
2319 av_dict_set(&st->metadata, "language", language, 0);
2320 }
2321 break;
2322 }
2323 if (ext_desc_tag == AC4_DESCRIPTOR) {
2324 st->codecpar->codec_id = AV_CODEC_ID_AC4;
2325 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2326 }
2327 break;
2328 case AC3_DESCRIPTOR:
2329 case ENHANCED_AC3_DESCRIPTOR:
2330 {
2331 int component_type_flag = get8(pp, desc_end) & (1 << 7);
2332 if (component_type_flag) {
2333 int component_type = get8(pp, desc_end);
2334 int service_type_mask = 0x38; // 0b00111000
2335 int service_type = ((component_type & service_type_mask) >> 3);
2336 if (service_type == 0x02 /* 0b010 */) {
2337 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2338 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2339 }
2340 }
2341 }
2342 break;
2343 case DATA_COMPONENT_DESCRIPTOR:
2344 // STD-B24, fascicle 3, chapter 4 defines private_stream_1
2345 // for captions
2346 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
2347 // This structure is defined in STD-B10, part 1, listing 5.4 and
2348 // part 2, 6.2.20).
2349 // Listing of data_component_ids is in STD-B10, part 2, Annex J.
2350 // Component tag limits are documented in TR-B14, fascicle 2,
2351 // Vol. 3, Section 2, 4.2.8.1
2352 int actual_component_tag = sti->stream_identifier - 1;
2353 int picked_profile = AV_PROFILE_UNKNOWN;
2354 int data_component_id = get16(pp, desc_end);
2355 if (data_component_id < 0)
2356 return AVERROR_INVALIDDATA;
2357
2358 switch (data_component_id) {
2359 case 0x0008:
2360 // [0x30..0x37] are component tags utilized for
2361 // non-mobile captioning service ("profile A").
2362 if (actual_component_tag >= 0x30 &&
2363 actual_component_tag <= 0x37) {
2364 picked_profile = AV_PROFILE_ARIB_PROFILE_A;
2365 }
2366 break;
2367 case 0x0012:
2368 // component tag 0x87 signifies a mobile/partial reception
2369 // (1seg) captioning service ("profile C").
2370 if (actual_component_tag == 0x87) {
2371 picked_profile = AV_PROFILE_ARIB_PROFILE_C;
2372 }
2373 break;
2374 default:
2375 break;
2376 }
2377
2378 if (picked_profile == AV_PROFILE_UNKNOWN)
2379 break;
2380
2381 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2382 st->codecpar->codec_id = AV_CODEC_ID_ARIB_CAPTION;
2383 if (st->codecpar->profile != picked_profile) {
2384 st->codecpar->profile = picked_profile;
2385 sti->need_context_update = 1;
2386 }
2387 sti->request_probe = 0;
2388 sti->need_parsing = 0;
2389 }
2390 break;
2391 case DOVI_VIDEO_STREAM_DESCRIPTOR:
2392 {
2393 uint32_t buf;
2394 AVDOVIDecoderConfigurationRecord *dovi;
2395 size_t dovi_size;
2396 int dependency_pid = -1; // Unset
2397
2398 if (desc_end - *pp < 4) // (8 + 8 + 7 + 6 + 1 + 1 + 1) / 8
2399 return AVERROR_INVALIDDATA;
2400
2401 dovi = av_dovi_alloc(&dovi_size);
2402 if (!dovi)
2403 return AVERROR(ENOMEM);
2404
2405 dovi->dv_version_major = get8(pp, desc_end);
2406 dovi->dv_version_minor = get8(pp, desc_end);
2407 buf = get16(pp, desc_end);
2408 dovi->dv_profile = (buf >> 9) & 0x7f; // 7 bits
2409 dovi->dv_level = (buf >> 3) & 0x3f; // 6 bits
2410 dovi->rpu_present_flag = (buf >> 2) & 0x01; // 1 bit
2411 dovi->el_present_flag = (buf >> 1) & 0x01; // 1 bit
2412 dovi->bl_present_flag = buf & 0x01; // 1 bit
2413 if (!dovi->bl_present_flag && desc_end - *pp >= 2) {
2414 buf = get16(pp, desc_end);
2415 dependency_pid = buf >> 3; // 13 bits
2416 }
2417 if (desc_end - *pp >= 1) { // 8 bits
2418 buf = get8(pp, desc_end);
2419 dovi->dv_bl_signal_compatibility_id = (buf >> 4) & 0x0f; // 4 bits
2420 dovi->dv_md_compression = (buf >> 2) & 0x03; // 2 bits
2421 } else {
2422 // 0 stands for None
2423 // Dolby Vision V1.2.93 profiles and levels
2424 dovi->dv_bl_signal_compatibility_id = 0;
2425 dovi->dv_md_compression = AV_DOVI_COMPRESSION_NONE;
2426 }
2427
2428 if (!av_packet_side_data_add(&st->codecpar->coded_side_data,
2429 &st->codecpar->nb_coded_side_data,
2430 AV_PKT_DATA_DOVI_CONF,
2431 (uint8_t *)dovi, dovi_size, 0)) {
2432 av_free(dovi);
2433 return AVERROR(ENOMEM);
2434 }
2435
2436 av_log(fc, AV_LOG_TRACE, "DOVI, version: %d.%d, profile: %d, level: %d, "
2437 "rpu flag: %d, el flag: %d, bl flag: %d, dependency_pid: %d, "
2438 "compatibility id: %d, compression: %d\n",
2439 dovi->dv_version_major, dovi->dv_version_minor,
2440 dovi->dv_profile, dovi->dv_level,
2441 dovi->rpu_present_flag,
2442 dovi->el_present_flag,
2443 dovi->bl_present_flag,
2444 dependency_pid,
2445 dovi->dv_bl_signal_compatibility_id,
2446 dovi->dv_md_compression);
2447 }
2448 break;
2449 case EXTENSION_DESCRIPTOR: /* descriptor extension */
2450 {
2451 int ret = parse_mpeg2_extension_descriptor(fc, st, prg_id, pp, desc_end);
2452
2453 if (ret < 0)
2454 return ret;
2455 }
2456 break;
2457 default:
2458 break;
2459 }
2460 *pp = desc_end;
2461 return 0;
2462 }
2463
2464 static AVStream *find_matching_stream(MpegTSContext *ts, int pid, unsigned int programid,
2465 int stream_identifier, int pmt_stream_idx, struct Program *p)
2466 {
2467 AVFormatContext *s = ts->stream;
2468 AVStream *found = NULL;
2469
2470 if (stream_identifier) { /* match based on "stream identifier descriptor" if present */
2471 for (int i = 0; i < p->nb_streams; i++) {
2472 if (p->streams[i].stream_identifier == stream_identifier)
2473 if (!found || pmt_stream_idx == i) /* fallback to idx based guess if multiple streams have the same identifier */
2474 found = s->streams[p->streams[i].idx];
2475 }
2476 } else if (pmt_stream_idx < p->nb_streams) { /* match based on position within the PMT */
2477 found = s->streams[p->streams[pmt_stream_idx].idx];
2478 }
2479
2480 if (found) {
2481 av_log(ts->stream, AV_LOG_VERBOSE,
2482 "reusing existing %s stream %d (pid=0x%x) for new pid=0x%x\n",
2483 av_get_media_type_string(found->codecpar->codec_type),
2484 found->index, found->id, pid);
2485 }
2486
2487 return found;
2488 }
2489
2490 static int parse_stream_identifier_desc(const uint8_t *p, const uint8_t *p_end)
2491 {
2492 const uint8_t **pp = &p;
2493 const uint8_t *desc_list_end;
2494 const uint8_t *desc_end;
2495 int desc_list_len;
2496 int desc_len, desc_tag;
2497
2498 desc_list_len = get16(pp, p_end);
2499 if (desc_list_len < 0)
2500 return -1;
2501 desc_list_len &= 0xfff;
2502 desc_list_end = p + desc_list_len;
2503 if (desc_list_end > p_end)
2504 return -1;
2505
2506 while (1) {
2507 desc_tag = get8(pp, desc_list_end);
2508 if (desc_tag < 0)
2509 return -1;
2510 desc_len = get8(pp, desc_list_end);
2511 if (desc_len < 0)
2512 return -1;
2513 desc_end = *pp + desc_len;
2514 if (desc_end > desc_list_end)
2515 return -1;
2516
2517 if (desc_tag == STREAM_IDENTIFIER_DESCRIPTOR) {
2518 return get8(pp, desc_end);
2519 }
2520 *pp = desc_end;
2521 }
2522
2523 return -1;
2524 }
2525
2526 static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
2527 {
2528 switch (stream_type) {
2529 case STREAM_TYPE_PRIVATE_SECTION:
2530 case STREAM_TYPE_ISO_IEC_14496_SECTION:
2531 return 0;
2532 case STREAM_TYPE_SCTE_DATA_SCTE_35:
2533 /* This User Private stream_type value is used by multiple organizations
2534 for different things. ANSI/SCTE 35 splice_info_section() is a
2535 private_section() not a PES_packet(). */
2536 return !(prog_reg_desc == AV_RL32("CUEI"));
2537 default:
2538 return 1;
2539 }
2540 }
2541
2542 static void create_stream_groups(MpegTSContext *ts, const struct Program *prg)
2543 {
2544 for (int i = 0; i < prg->nb_stream_groups; i++) {
2545 const struct StreamGroup *grp = &prg->stream_groups[i];
2546 AVStreamGroup *stg;
2547 int j;
2548 if (grp->nb_streams < 2)
2549 continue;
2550 for (j = 0; j < ts->stream->nb_stream_groups; j++) {
2551 stg = ts->stream->stream_groups[j];
2552 if (stg->id == grp->id)
2553 break;
2554 }
2555 if (j == ts->stream->nb_stream_groups)
2556 stg = avformat_stream_group_create(ts->stream, grp->type, NULL);
2557 else
2558 continue;
2559 if (!stg)
2560 continue;
2561 av_assert0(grp->type == AV_STREAM_GROUP_PARAMS_LCEVC);
2562 stg->id = grp->id;
2563 for (int j = 0; j < grp->nb_streams; j++) {
2564 int ret = avformat_stream_group_add_stream(stg, grp->streams[j]);
2565 if (ret < 0) {
2566 ff_remove_stream_group(ts->stream, stg);
2567 continue;
2568 }
2569 if (grp->streams[j]->codecpar->codec_id == AV_CODEC_ID_LCEVC)
2570 stg->params.lcevc->lcevc_index = stg->nb_streams - 1;
2571 }
2572 }
2573 }
2574
2575 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2576 {
2577 MpegTSContext *ts = filter->u.section_filter.opaque;
2578 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2579 struct Program old_program;
2580 SectionHeader h1, *h = &h1;
2581 PESContext *pes;
2582 AVStream *st;
2583 const uint8_t *p, *p_end, *desc_list_end;
2584 int program_info_length, pcr_pid, pid, stream_type;
2585 int desc_list_len;
2586 uint32_t prog_reg_desc = 0; /* registration descriptor */
2587 int stream_identifier = -1;
2588 struct Program *prg;
2589
2590 int mp4_descr_count = 0;
2591 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
2592 int i;
2593
2594 av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
2595 hex_dump_debug(ts->stream, section, section_len);
2596
2597 p_end = section + section_len - 4;
2598 p = section;
2599 if (parse_section_header(h, &p, p_end) < 0)
2600 return;
2601 if (h->tid != PMT_TID)
2602 return;
2603 if (!h->current_next)
2604 return;
2605 if (skip_identical(h, tssf))
2606 return;
2607
2608 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
2609 h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
2610
2611 if (!ts->scan_all_pmts && ts->skip_changes)
2612 return;
2613
2614 prg = get_program(ts, h->id);
2615 if (prg)
2616 old_program = *prg;
2617 else
2618 clear_program(&old_program);
2619
2620 if (ts->skip_unknown_pmt && !prg)
2621 return;
2622 if (prg && prg->nb_pids && prg->pids[0] != ts->current_pid)
2623 return;
2624 if (!ts->skip_clear)
2625 clear_avprogram(ts, h->id);
2626 clear_program(prg);
2627 add_pid_to_program(prg, ts->current_pid);
2628
2629 pcr_pid = get16(&p, p_end);
2630 if (pcr_pid < 0)
2631 return;
2632 pcr_pid &= 0x1fff;
2633 add_pid_to_program(prg, pcr_pid);
2634 update_av_program_info(ts->stream, h->id, pcr_pid, h->version);
2635
2636 av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
2637
2638 program_info_length = get16(&p, p_end);
2639
2640 if (program_info_length < 0 || (program_info_length & 0xFFF) > p_end - p)
2641 return;
2642 program_info_length &= 0xfff;
2643 while (program_info_length >= 2) {
2644 uint8_t tag, len;
2645 tag = get8(&p, p_end);
2646 len = get8(&p, p_end);
2647
2648 av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
2649
2650 program_info_length -= 2;
2651 if (len > program_info_length)
2652 // something else is broken, exit the program_descriptors_loop
2653 break;
2654 program_info_length -= len;
2655 if (tag == IOD_DESCRIPTOR && len >= 2) {
2656 get8(&p, p_end); // scope
2657 get8(&p, p_end); // label
2658 len -= 2;
2659 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
2660 &mp4_descr_count, MAX_MP4_DESCR_COUNT - mp4_descr_count);
2661 } else if (tag == REGISTRATION_DESCRIPTOR && len >= 4) {
2662 prog_reg_desc = bytestream_get_le32(&p);
2663 len -= 4;
2664 }
2665 p += len;
2666 }
2667 p += program_info_length;
2668 if (p >= p_end)
2669 goto out;
2670
2671 // stop parsing after pmt, we found header
2672 if (!ts->pkt)
2673 ts->stop_parse = 2;
2674
2675 if (prg)
2676 prg->pmt_found = 1;
2677
2678 for (i = 0; i < MAX_STREAMS_PER_PROGRAM; i++) {
2679 st = 0;
2680 pes = NULL;
2681 stream_type = get8(&p, p_end);
2682 if (stream_type < 0)
2683 break;
2684 pid = get16(&p, p_end);
2685 if (pid < 0)
2686 goto out;
2687 pid &= 0x1fff;
2688 if (pid == ts->current_pid)
2689 goto out;
2690
2691 stream_identifier = parse_stream_identifier_desc(p, p_end) + 1;
2692
2693 /* now create stream */
2694 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
2695 pes = ts->pids[pid]->u.pes_filter.opaque;
2696 if (ts->merge_pmt_versions && !pes->st) {
2697 st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
2698 if (st) {
2699 pes->st = st;
2700 pes->stream_type = stream_type;
2701 pes->merged_st = 1;
2702 }
2703 }
2704 if (!pes->st) {
2705 pes->st = avformat_new_stream(pes->stream, NULL);
2706 if (!pes->st)
2707 goto out;
2708 pes->st->id = pes->pid;
2709 }
2710 st = pes->st;
2711 } else if (is_pes_stream(stream_type, prog_reg_desc)) {
2712 if (ts->pids[pid])
2713 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
2714 pes = add_pes_stream(ts, pid, pcr_pid);
2715 if (ts->merge_pmt_versions && pes && !pes->st) {
2716 st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
2717 if (st) {
2718 pes->st = st;
2719 pes->stream_type = stream_type;
2720 pes->merged_st = 1;
2721 }
2722 }
2723 if (pes && !pes->st) {
2724 st = avformat_new_stream(pes->stream, NULL);
2725 if (!st)
2726 goto out;
2727 st->id = pes->pid;
2728 }
2729 } else {
2730 int idx = ff_find_stream_index(ts->stream, pid);
2731 if (idx >= 0) {
2732 st = ts->stream->streams[idx];
2733 }
2734 if (ts->merge_pmt_versions && !st) {
2735 st = find_matching_stream(ts, pid, h->id, stream_identifier, i, &old_program);
2736 }
2737 if (!st) {
2738 st = avformat_new_stream(ts->stream, NULL);
2739 if (!st)
2740 goto out;
2741 st->id = pid;
2742 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2743 if (stream_type == STREAM_TYPE_SCTE_DATA_SCTE_35 && prog_reg_desc == AV_RL32("CUEI")) {
2744 mpegts_find_stream_type(st, stream_type, SCTE_types);
2745 mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
2746 }
2747 }
2748 }
2749
2750 if (!st)
2751 goto out;
2752
2753 if (pes && pes->stream_type != stream_type)
2754 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
2755
2756 add_pid_to_program(prg, pid);
2757 if (prg) {
2758 prg->streams[i].idx = st->index;
2759 prg->streams[i].stream_identifier = stream_identifier;
2760 prg->nb_streams++;
2761 }
2762
2763 av_program_add_stream_index(ts->stream, h->id, st->index);
2764
2765 desc_list_len = get16(&p, p_end);
2766 if (desc_list_len < 0)
2767 goto out;
2768 desc_list_len &= 0xfff;
2769 desc_list_end = p + desc_list_len;
2770 if (desc_list_end > p_end)
2771 goto out;
2772 for (;;) {
2773 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, h->id, &p,
2774 desc_list_end, mp4_descr,
2775 mp4_descr_count, pid, ts) < 0)
2776 break;
2777
2778 if (pes && prog_reg_desc == AV_RL32("HDMV") &&
2779 stream_type == STREAM_TYPE_BLURAY_AUDIO_TRUEHD && pes->sub_st) {
2780 av_program_add_stream_index(ts->stream, h->id,
2781 pes->sub_st->index);
2782 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
2783 }
2784 }
2785 p = desc_list_end;
2786 }
2787
2788 if (!ts->pids[pcr_pid])
2789 mpegts_open_pcr_filter(ts, pcr_pid);
2790
2791 out:
2792 if (prg)
2793 create_stream_groups(ts, prg);
2794
2795 for (i = 0; i < mp4_descr_count; i++)
2796 av_free(mp4_descr[i].dec_config_descr);
2797 }
2798
2799 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2800 {
2801 MpegTSContext *ts = filter->u.section_filter.opaque;
2802 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2803 SectionHeader h1, *h = &h1;
2804 const uint8_t *p, *p_end;
2805 int sid, pmt_pid;
2806 int nb_prg = 0;
2807 AVProgram *program;
2808
2809 av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
2810 hex_dump_debug(ts->stream, section, section_len);
2811
2812 p_end = section + section_len - 4;
2813 p = section;
2814 if (parse_section_header(h, &p, p_end) < 0)
2815 return;
2816 if (h->tid != PAT_TID)
2817 return;
2818 if (!h->current_next)
2819 return;
2820 if (ts->skip_changes)
2821 return;
2822
2823 if (skip_identical(h, tssf))
2824 return;
2825 ts->id = h->id;
2826
2827 for (;;) {
2828 sid = get16(&p, p_end);
2829 if (sid < 0)
2830 break;
2831 pmt_pid = get16(&p, p_end);
2832 if (pmt_pid < 0)
2833 break;
2834 pmt_pid &= 0x1fff;
2835
2836 if (pmt_pid <= 0x000F || pmt_pid == 0x1FFF) {
2837 av_log(ts->stream, AV_LOG_WARNING,
2838 "Ignoring invalid PAT entry: sid=0x%x pid=0x%x\n", sid, pmt_pid);
2839 continue;
2840 }
2841
2842 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
2843
2844 if (sid == 0x0000) {
2845 /* NIT info */
2846 } else {
2847 MpegTSFilter *fil = ts->pids[pmt_pid];
2848 struct Program *prg;
2849 program = av_new_program(ts->stream, sid);
2850 if (program) {
2851 program->program_num = sid;
2852 program->pmt_pid = pmt_pid;
2853 }
2854 if (fil)
2855 if ( fil->type != MPEGTS_SECTION
2856 || fil->pid != pmt_pid
2857 || fil->u.section_filter.section_cb != pmt_cb)
2858 mpegts_close_filter(ts, ts->pids[pmt_pid]);
2859
2860 if (!ts->pids[pmt_pid])
2861 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
2862 prg = add_program(ts, sid);
2863 if (prg) {
2864 unsigned prg_idx = prg - ts->prg;
2865 if (prg->nb_pids && prg->pids[0] != pmt_pid)
2866 clear_program(prg);
2867 add_pid_to_program(prg, pmt_pid);
2868 if (prg_idx > nb_prg)
2869 FFSWAP(struct Program, ts->prg[nb_prg], ts->prg[prg_idx]);
2870 if (prg_idx >= nb_prg)
2871 nb_prg++;
2872 } else
2873 nb_prg = 0;
2874 }
2875 }
2876 ts->nb_prg = nb_prg;
2877
2878 if (sid < 0) {
2879 int i,j;
2880 for (j=0; j<ts->stream->nb_programs; j++) {
2881 for (i = 0; i < ts->nb_prg; i++)
2882 if (ts->prg[i].id == ts->stream->programs[j]->id)
2883 break;
2884 if (i==ts->nb_prg && !ts->skip_clear)
2885 clear_avprogram(ts, ts->stream->programs[j]->id);
2886 }
2887 }
2888 }
2889
2890 static void eit_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2891 {
2892 MpegTSContext *ts = filter->u.section_filter.opaque;
2893 const uint8_t *p, *p_end;
2894 SectionHeader h1, *h = &h1;
2895
2896 /*
2897 * Sometimes we receive EPG packets but SDT table do not have
2898 * eit_pres_following or eit_sched turned on, so we open EPG
2899 * stream directly here.
2900 */
2901 if (!ts->epg_stream) {
2902 ts->epg_stream = avformat_new_stream(ts->stream, NULL);
2903 if (!ts->epg_stream)
2904 return;
2905 ts->epg_stream->id = EIT_PID;
2906 ts->epg_stream->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2907 ts->epg_stream->codecpar->codec_id = AV_CODEC_ID_EPG;
2908 }
2909
2910 if (ts->epg_stream->discard == AVDISCARD_ALL)
2911 return;
2912
2913 p_end = section + section_len - 4;
2914 p = section;
2915
2916 if (parse_section_header(h, &p, p_end) < 0)
2917 return;
2918 if (h->tid < EIT_TID || h->tid > OEITS_END_TID)
2919 return;
2920
2921 av_log(ts->stream, AV_LOG_TRACE, "EIT: tid received = %.02x\n", h->tid);
2922
2923 /**
2924 * Service_id 0xFFFF is reserved, it indicates that the current EIT table
2925 * is scrambled.
2926 */
2927 if (h->id == 0xFFFF) {
2928 av_log(ts->stream, AV_LOG_TRACE, "Scrambled EIT table received.\n");
2929 return;
2930 }
2931
2932 /**
2933 * In case we receive an EPG packet before mpegts context is fully
2934 * initialized.
2935 */
2936 if (!ts->pkt)
2937 return;
2938
2939 new_data_packet(section, section_len, ts->pkt);
2940 ts->pkt->stream_index = ts->epg_stream->index;
2941 ts->stop_parse = 1;
2942 }
2943
2944 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2945 {
2946 MpegTSContext *ts = filter->u.section_filter.opaque;
2947 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2948 SectionHeader h1, *h = &h1;
2949 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
2950 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
2951 char *name, *provider_name;
2952
2953 av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
2954 hex_dump_debug(ts->stream, section, section_len);
2955
2956 p_end = section + section_len - 4;
2957 p = section;
2958 if (parse_section_header(h, &p, p_end) < 0)
2959 return;
2960 if (h->tid != SDT_TID)
2961 return;
2962 if (!h->current_next)
2963 return;
2964 if (ts->skip_changes)
2965 return;
2966 if (skip_identical(h, tssf))
2967 return;
2968
2969 onid = get16(&p, p_end);
2970 if (onid < 0)
2971 return;
2972 val = get8(&p, p_end);
2973 if (val < 0)
2974 return;
2975 for (;;) {
2976 sid = get16(&p, p_end);
2977 if (sid < 0)
2978 break;
2979 val = get8(&p, p_end);
2980 if (val < 0)
2981 break;
2982 desc_list_len = get16(&p, p_end);
2983 if (desc_list_len < 0)
2984 break;
2985 desc_list_len &= 0xfff;
2986 desc_list_end = p + desc_list_len;
2987 if (desc_list_end > p_end)
2988 break;
2989 for (;;) {
2990 desc_tag = get8(&p, desc_list_end);
2991 if (desc_tag < 0)
2992 break;
2993 desc_len = get8(&p, desc_list_end);
2994 desc_end = p + desc_len;
2995 if (desc_len < 0 || desc_end > desc_list_end)
2996 break;
2997
2998 av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
2999 desc_tag, desc_len);
3000
3001 switch (desc_tag) {
3002 case SERVICE_DESCRIPTOR:
3003 service_type = get8(&p, desc_end);
3004 if (service_type < 0)
3005 break;
3006 provider_name = getstr8(&p, desc_end);
3007 if (!provider_name)
3008 break;
3009 name = getstr8(&p, desc_end);
3010 if (name) {
3011 AVProgram *program = av_new_program(ts->stream, sid);
3012 if (program) {
3013 av_dict_set(&program->metadata, "service_name", name, 0);
3014 av_dict_set(&program->metadata, "service_provider",
3015 provider_name, 0);
3016 }
3017 }
3018 av_free(name);
3019 av_free(provider_name);
3020 break;
3021 default:
3022 break;
3023 }
3024 p = desc_end;
3025 }
3026 p = desc_list_end;
3027 }
3028 }
3029
3030 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
3031 const uint8_t *packet);
3032
3033 /* handle one TS packet */
3034 static int handle_packet(MpegTSContext *ts, const uint8_t *packet, int64_t pos)
3035 {
3036 MpegTSFilter *tss;
3037 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
3038 has_adaptation, has_payload;
3039 const uint8_t *p, *p_end;
3040
3041 pid = AV_RB16(packet + 1) & 0x1fff;
3042 is_start = packet[1] & 0x40;
3043 tss = ts->pids[pid];
3044 if (ts->auto_guess && !tss && is_start) {
3045 add_pes_stream(ts, pid, -1);
3046 tss = ts->pids[pid];
3047 }
3048 if (!tss)
3049 return 0;
3050 if (is_start)
3051 tss->discard = discard_pid(ts, pid);
3052 if (tss->discard)
3053 return 0;
3054 ts->current_pid = pid;
3055
3056 afc = (packet[3] >> 4) & 3;
3057 if (afc == 0) /* reserved value */
3058 return 0;
3059 has_adaptation = afc & 2;
3060 has_payload = afc & 1;
3061 is_discontinuity = has_adaptation &&
3062 packet[4] != 0 && /* with length > 0 */
3063 (packet[5] & 0x80); /* and discontinuity indicated */
3064
3065 /* continuity check (currently not used) */
3066 cc = (packet[3] & 0xf);
3067 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
3068 cc_ok = pid == NULL_PID ||
3069 is_discontinuity ||
3070 tss->last_cc < 0 ||
3071 expected_cc == cc;
3072
3073 tss->last_cc = cc;
3074 if (!cc_ok) {
3075 av_log(ts->stream, AV_LOG_DEBUG,
3076 "Continuity check failed for pid %d expected %d got %d\n",
3077 pid, expected_cc, cc);
3078 if (tss->type == MPEGTS_PES) {
3079 PESContext *pc = tss->u.pes_filter.opaque;
3080 pc->flags |= AV_PKT_FLAG_CORRUPT;
3081 }
3082 }
3083
3084 if (packet[1] & 0x80) {
3085 av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
3086 if (tss->type == MPEGTS_PES) {
3087 PESContext *pc = tss->u.pes_filter.opaque;
3088 pc->flags |= AV_PKT_FLAG_CORRUPT;
3089 }
3090 }
3091
3092 p = packet + 4;
3093 if (has_adaptation) {
3094 int64_t pcr_h;
3095 int pcr_l;
3096 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
3097 tss->last_pcr = pcr_h * SYSTEM_CLOCK_FREQUENCY_DIVISOR + pcr_l;
3098 /* skip adaptation field */
3099 p += p[0] + 1;
3100 }
3101 /* if past the end of packet, ignore */
3102 p_end = packet + TS_PACKET_SIZE;
3103 if (p >= p_end || !has_payload)
3104 return 0;
3105
3106 if (pos >= 0) {
3107 av_assert0(pos >= TS_PACKET_SIZE);
3108 ts->pos47_full = pos - TS_PACKET_SIZE;
3109 }
3110
3111 if (tss->type == MPEGTS_SECTION) {
3112 if (is_start) {
3113 /* pointer field present */
3114 len = *p++;
3115 if (len > p_end - p)
3116 return 0;
3117 if (len && cc_ok) {
3118 /* write remaining section bytes */
3119 write_section_data(ts, tss,
3120 p, len, 0);
3121 /* check whether filter has been closed */
3122 if (!ts->pids[pid])
3123 return 0;
3124 }
3125 p += len;
3126 if (p < p_end) {
3127 write_section_data(ts, tss,
3128 p, p_end - p, 1);
3129 }
3130 } else {
3131 if (cc_ok) {
3132 write_section_data(ts, tss,
3133 p, p_end - p, 0);
3134 }
3135 }
3136
3137 // stop find_stream_info from waiting for more streams
3138 // when all programs have received a PMT
3139 if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
3140 int i;
3141 for (i = 0; i < ts->nb_prg; i++) {
3142 if (!ts->prg[i].pmt_found)
3143 break;
3144 }
3145 if (i == ts->nb_prg && ts->nb_prg > 0) {
3146 av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
3147 ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
3148 }
3149 }
3150
3151 } else {
3152 int ret;
3153 // Note: The position here points actually behind the current packet.
3154 if (tss->type == MPEGTS_PES) {
3155 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
3156 pos - ts->raw_packet_size)) < 0)
3157 return ret;
3158 }
3159 }
3160
3161 return 0;
3162 }
3163
3164 static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
3165 {
3166 MpegTSContext *ts = s->priv_data;
3167 AVIOContext *pb = s->pb;
3168 int c, i;
3169 uint64_t pos = avio_tell(pb);
3170 int64_t back = FFMIN(seekback, pos);
3171
3172 //Special case for files like 01c56b0dc1.ts
3173 if (current_packet[0] == 0x80 && current_packet[12] == SYNC_BYTE && pos >= TS_PACKET_SIZE) {
3174 avio_seek(pb, 12 - TS_PACKET_SIZE, SEEK_CUR);
3175 return 0;
3176 }
3177
3178 avio_seek(pb, -back, SEEK_CUR);
3179
3180 for (i = 0; i < ts->resync_size; i++) {
3181 c = avio_r8(pb);
3182 if (avio_feof(pb))
3183 return AVERROR_EOF;
3184 if (c == SYNC_BYTE) {
3185 int new_packet_size, ret;
3186 avio_seek(pb, -1, SEEK_CUR);
3187 pos = avio_tell(pb);
3188 ret = ffio_ensure_seekback(pb, PROBE_PACKET_MAX_BUF);
3189 if (ret < 0)
3190 return ret;
3191 new_packet_size = get_packet_size(s);
3192 if (new_packet_size > 0 && new_packet_size != ts->raw_packet_size) {
3193 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", new_packet_size);
3194 ts->raw_packet_size = new_packet_size;
3195 }
3196 avio_seek(pb, pos, SEEK_SET);
3197 return 0;
3198 }
3199 }
3200 av_log(s, AV_LOG_ERROR,
3201 "max resync size reached, could not find sync byte\n");
3202 /* no sync found */
3203 return AVERROR_INVALIDDATA;
3204 }
3205
3206 /* return AVERROR_something if error or EOF. Return 0 if OK. */
3207 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
3208 const uint8_t **data)
3209 {
3210 AVIOContext *pb = s->pb;
3211 int len;
3212
3213 // 192 bytes source packet that start with a 4 bytes TP_extra_header
3214 // followed by 188 bytes of TS packet. The sync byte is at offset 4, so skip
3215 // the first 4 bytes otherwise we'll end up syncing to the wrong packet.
3216 if (raw_packet_size == TS_DVHS_PACKET_SIZE)
3217 avio_skip(pb, 4);
3218
3219 for (;;) {
3220 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
3221 if (len != TS_PACKET_SIZE)
3222 return len < 0 ? len : AVERROR_EOF;
3223 /* check packet sync byte */
3224 if ((*data)[0] != SYNC_BYTE) {
3225 /* find a new packet start */
3226
3227 if (mpegts_resync(s, raw_packet_size, *data) < 0)
3228 return AVERROR(EAGAIN);
3229 else
3230 continue;
3231 } else {
3232 break;
3233 }
3234 }
3235 return 0;
3236 }
3237
3238 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
3239 {
3240 AVIOContext *pb = s->pb;
3241 int skip;
3242 if (raw_packet_size == TS_DVHS_PACKET_SIZE)
3243 skip = raw_packet_size - TS_DVHS_PACKET_SIZE;
3244 else
3245 skip = raw_packet_size - TS_PACKET_SIZE;
3246 if (skip > 0)
3247 avio_skip(pb, skip);
3248 }
3249
3250 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
3251 {
3252 AVFormatContext *s = ts->stream;
3253 uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
3254 const uint8_t *data;
3255 int64_t packet_num;
3256 int ret = 0;
3257
3258 if (avio_tell(s->pb) != ts->last_pos) {
3259 int i;
3260 av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
3261 /* seek detected, flush pes buffer */
3262 for (i = 0; i < NB_PID_MAX; i++) {
3263 if (ts->pids[i]) {
3264 if (ts->pids[i]->type == MPEGTS_PES) {
3265 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3266 av_buffer_unref(&pes->buffer);
3267 pes->data_index = 0;
3268 pes->state = MPEGTS_SKIP; /* skip until pes header */
3269 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
3270 ts->pids[i]->u.section_filter.last_ver = -1;
3271 }
3272 ts->pids[i]->last_cc = -1;
3273 ts->pids[i]->last_pcr = -1;
3274 }
3275 }
3276 }
3277
3278 ts->stop_parse = 0;
3279 packet_num = 0;
3280 memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3281 for (;;) {
3282 packet_num++;
3283 if (nb_packets != 0 && packet_num >= nb_packets ||
3284 ts->stop_parse > 1) {
3285 ret = AVERROR(EAGAIN);
3286 break;
3287 }
3288 if (ts->stop_parse > 0)
3289 break;
3290
3291 ret = read_packet(s, packet, ts->raw_packet_size, &data);
3292 if (ret != 0)
3293 break;
3294 ret = handle_packet(ts, data, avio_tell(s->pb));
3295 finished_reading_packet(s, ts->raw_packet_size);
3296 if (ret != 0)
3297 break;
3298 }
3299 ts->last_pos = avio_tell(s->pb);
3300 return ret;
3301 }
3302
3303 static int mpegts_probe(const AVProbeData *p)
3304 {
3305 const int size = p->buf_size;
3306 int maxscore = 0;
3307 int sumscore = 0;
3308 int i;
3309 int check_count = size / TS_FEC_PACKET_SIZE;
3310 #define CHECK_COUNT 10
3311 #define CHECK_BLOCK 100
3312
3313 if (!check_count)
3314 return 0;
3315
3316 for (i = 0; i<check_count; i+=CHECK_BLOCK) {
3317 int left = FFMIN(check_count - i, CHECK_BLOCK);
3318 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
3319 int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
3320 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
3321 score = FFMAX3(score, dvhs_score, fec_score);
3322 sumscore += score;
3323 maxscore = FFMAX(maxscore, score);
3324 }
3325
3326 sumscore = sumscore * CHECK_COUNT / check_count;
3327 maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
3328
3329 ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
3330
3331 if (check_count > CHECK_COUNT && sumscore > 6) {
3332 return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
3333 } else if (check_count >= CHECK_COUNT && sumscore > 6) {
3334 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
3335 } else if (check_count >= CHECK_COUNT && maxscore > 6) {
3336 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
3337 } else if (sumscore > 6) {
3338 return 2;
3339 } else {
3340 return 0;
3341 }
3342 }
3343
3344 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
3345 * (-1) if not available */
3346 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
3347 {
3348 int afc, len, flags;
3349 const uint8_t *p;
3350 unsigned int v;
3351
3352 afc = (packet[3] >> 4) & 3;
3353 if (afc <= 1)
3354 return AVERROR_INVALIDDATA;
3355 p = packet + 4;
3356 len = p[0];
3357 p++;
3358 if (len == 0)
3359 return AVERROR_INVALIDDATA;
3360 flags = *p++;
3361 len--;
3362 if (!(flags & 0x10))
3363 return AVERROR_INVALIDDATA;
3364 if (len < 6)
3365 return AVERROR_INVALIDDATA;
3366 v = AV_RB32(p);
3367 *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
3368 *ppcr_low = ((p[4] & 1) << 8) | p[5];
3369 return 0;
3370 }
3371
3372 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
3373
3374 /* NOTE: We attempt to seek on non-seekable files as well, as the
3375 * probe buffer usually is big enough. Only warn if the seek failed
3376 * on files where the seek should work. */
3377 if (avio_seek(pb, pos, SEEK_SET) < 0)
3378 av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
3379 }
3380
3381 static int mpegts_read_header(AVFormatContext *s)
3382 {
3383 MpegTSContext *ts = s->priv_data;
3384 AVIOContext *pb = s->pb;
3385 int64_t pos, probesize = s->probesize;
3386 int64_t seekback = FFMAX(s->probesize, (int64_t)ts->resync_size + PROBE_PACKET_MAX_BUF);
3387
3388 if (ffio_ensure_seekback(pb, seekback) < 0)
3389 av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
3390
3391 pos = avio_tell(pb);
3392 ts->raw_packet_size = get_packet_size(s);
3393 if (ts->raw_packet_size <= 0) {
3394 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
3395 ts->raw_packet_size = TS_PACKET_SIZE;
3396 }
3397 ts->stream = s;
3398 ts->auto_guess = 0;
3399
3400 if (s->iformat == &ff_mpegts_demuxer.p) {
3401 /* normal demux */
3402
3403 /* first do a scan to get all the services */
3404 seek_back(s, pb, pos);
3405
3406 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3407 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3408 mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
3409
3410 handle_packets(ts, probesize / ts->raw_packet_size);
3411 /* if could not find service, enable auto_guess */
3412
3413 ts->auto_guess = 1;
3414
3415 av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
3416
3417 s->ctx_flags |= AVFMTCTX_NOHEADER;
3418 } else {
3419 AVStream *st;
3420 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
3421 int64_t pcrs[2], pcr_h;
3422 uint8_t packet[TS_PACKET_SIZE];
3423 const uint8_t *data;
3424
3425 /* only read packets */
3426
3427 st = avformat_new_stream(s, NULL);
3428 if (!st)
3429 return AVERROR(ENOMEM);
3430 avpriv_set_pts_info(st, 60, 1, 27000000);
3431 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3432 st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
3433
3434 /* we iterate until we find two PCRs to estimate the bitrate */
3435 pcr_pid = -1;
3436 nb_pcrs = 0;
3437 nb_packets = 0;
3438 for (;;) {
3439 ret = read_packet(s, packet, ts->raw_packet_size, &data);
3440 if (ret < 0)
3441 return ret;
3442 pid = AV_RB16(data + 1) & 0x1fff;
3443 if ((pcr_pid == -1 || pcr_pid == pid) &&
3444 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
3445 finished_reading_packet(s, ts->raw_packet_size);
3446 pcr_pid = pid;
3447 pcrs[nb_pcrs] = pcr_h * SYSTEM_CLOCK_FREQUENCY_DIVISOR + pcr_l;
3448 nb_pcrs++;
3449 if (nb_pcrs >= 2) {
3450 if (pcrs[1] - pcrs[0] > 0) {
3451 /* the difference needs to be positive to make sense for bitrate computation */
3452 break;
3453 } else {
3454 av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
3455 pcrs[0] = pcrs[1];
3456 nb_pcrs--;
3457 }
3458 }
3459 } else {
3460 finished_reading_packet(s, ts->raw_packet_size);
3461 }
3462 nb_packets++;
3463 }
3464
3465 /* NOTE1: the bitrate is computed without the FEC */
3466 /* NOTE2: it is only the bitrate of the start of the stream */
3467 ts->pcr_incr = pcrs[1] - pcrs[0];
3468 ts->cur_pcr = pcrs[0] - ts->pcr_incr * (nb_packets - 1);
3469 s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
3470 st->codecpar->bit_rate = s->bit_rate;
3471 st->start_time = ts->cur_pcr;
3472 av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%"PRId64"\n",
3473 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
3474 }
3475
3476 seek_back(s, pb, pos);
3477 return 0;
3478 }
3479
3480 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
3481
3482 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
3483 {
3484 MpegTSContext *ts = s->priv_data;
3485 int ret, i;
3486 int64_t pcr_h, next_pcr_h, pos;
3487 int pcr_l, next_pcr_l;
3488 uint8_t pcr_buf[12];
3489 const uint8_t *data;
3490
3491 if ((ret = av_new_packet(pkt, TS_PACKET_SIZE)) < 0)
3492 return ret;
3493 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
3494 pkt->pos = avio_tell(s->pb);
3495 if (ret < 0) {
3496 return ret;
3497 }
3498 if (data != pkt->data)
3499 memcpy(pkt->data, data, TS_PACKET_SIZE);
3500 finished_reading_packet(s, ts->raw_packet_size);
3501 if (ts->mpeg2ts_compute_pcr) {
3502 /* compute exact PCR for each packet */
3503 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
3504 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
3505 pos = avio_tell(s->pb);
3506 for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
3507 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
3508 avio_read(s->pb, pcr_buf, 12);
3509 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
3510 /* XXX: not precise enough */
3511 ts->pcr_incr =
3512 ((next_pcr_h - pcr_h) * SYSTEM_CLOCK_FREQUENCY_DIVISOR + (next_pcr_l - pcr_l)) /
3513 (i + 1);
3514 break;
3515 }
3516 }
3517 avio_seek(s->pb, pos, SEEK_SET);
3518 /* no next PCR found: we use previous increment */
3519 ts->cur_pcr = pcr_h * SYSTEM_CLOCK_FREQUENCY_DIVISOR + pcr_l;
3520 }
3521 pkt->pts = ts->cur_pcr;
3522 pkt->duration = ts->pcr_incr;
3523 ts->cur_pcr += ts->pcr_incr;
3524 }
3525 pkt->stream_index = 0;
3526 return 0;
3527 }
3528
3529 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
3530 {
3531 MpegTSContext *ts = s->priv_data;
3532 int ret, i;
3533
3534 pkt->size = -1;
3535 ts->pkt = pkt;
3536 ret = handle_packets(ts, 0);
3537 if (ret < 0) {
3538 av_packet_unref(ts->pkt);
3539 /* flush pes data left */
3540 for (i = 0; i < NB_PID_MAX; i++)
3541 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
3542 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3543 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
3544 ret = new_pes_packet(pes, pkt);
3545 if (ret < 0)
3546 return ret;
3547 pes->state = MPEGTS_SKIP;
3548 ret = 0;
3549 break;
3550 }
3551 }
3552 }
3553
3554 if (!ret && pkt->size < 0)
3555 ret = AVERROR_INVALIDDATA;
3556 return ret;
3557 }
3558
3559 static void mpegts_free(MpegTSContext *ts)
3560 {
3561 int i;
3562
3563 clear_programs(ts);
3564
3565 for (i = 0; i < FF_ARRAY_ELEMS(ts->pools); i++)
3566 av_buffer_pool_uninit(&ts->pools[i]);
3567
3568 for (i = 0; i < NB_PID_MAX; i++)
3569 if (ts->pids[i])
3570 mpegts_close_filter(ts, ts->pids[i]);
3571 }
3572
3573 static int mpegts_read_close(AVFormatContext *s)
3574 {
3575 MpegTSContext *ts = s->priv_data;
3576 mpegts_free(ts);
3577 return 0;
3578 }
3579
3580 av_unused static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
3581 int64_t *ppos, int64_t pos_limit)
3582 {
3583 MpegTSContext *ts = s->priv_data;
3584 int64_t pos, timestamp;
3585 uint8_t buf[TS_PACKET_SIZE];
3586 int pcr_l, pcr_pid =
3587 ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
3588 int pos47 = ts->pos47_full % ts->raw_packet_size;
3589 pos =
3590 ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
3591 ts->raw_packet_size + pos47;
3592 while(pos < pos_limit) {
3593 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3594 return AV_NOPTS_VALUE;
3595 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
3596 return AV_NOPTS_VALUE;
3597 if (buf[0] != SYNC_BYTE) {
3598 if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
3599 return AV_NOPTS_VALUE;
3600 pos = avio_tell(s->pb);
3601 continue;
3602 }
3603 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
3604 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
3605 *ppos = pos;
3606 return timestamp;
3607 }
3608 pos += ts->raw_packet_size;
3609 }
3610
3611 return AV_NOPTS_VALUE;
3612 }
3613
3614 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
3615 int64_t *ppos, int64_t pos_limit)
3616 {
3617 MpegTSContext *ts = s->priv_data;
3618 AVPacket *pkt;
3619 int64_t pos;
3620 int pos47 = ts->pos47_full % ts->raw_packet_size;
3621 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
3622 ff_read_frame_flush(s);
3623 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3624 return AV_NOPTS_VALUE;
3625 pkt = av_packet_alloc();
3626 if (!pkt)
3627 return AV_NOPTS_VALUE;
3628 while(pos < pos_limit) {
3629 int ret = av_read_frame(s, pkt);
3630 if (ret < 0) {
3631 av_packet_free(&pkt);
3632 return AV_NOPTS_VALUE;
3633 }
3634 if (pkt->dts != AV_NOPTS_VALUE && pkt->pos >= 0) {
3635 ff_reduce_index(s, pkt->stream_index);
3636 av_add_index_entry(s->streams[pkt->stream_index], pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
3637 if (pkt->stream_index == stream_index && pkt->pos >= *ppos) {
3638 int64_t dts = pkt->dts;
3639 *ppos = pkt->pos;
3640 av_packet_free(&pkt);
3641 return dts;
3642 }
3643 }
3644 pos = pkt->pos;
3645 av_packet_unref(pkt);
3646 }
3647
3648 av_packet_free(&pkt);
3649 return AV_NOPTS_VALUE;
3650 }
3651
3652 /**************************************************************/
3653 /* parsing functions - called from other demuxers such as RTP */
3654
3655 MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
3656 {
3657 MpegTSContext *ts;
3658
3659 ts = av_mallocz(sizeof(MpegTSContext));
3660 if (!ts)
3661 return NULL;
3662 /* no stream case, currently used by RTP */
3663 ts->raw_packet_size = TS_PACKET_SIZE;
3664 ts->max_packet_size = 2048000;
3665 ts->stream = s;
3666 ts->auto_guess = 1;
3667
3668 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3669 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3670 mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
3671
3672 return ts;
3673 }
3674
3675 /* return the consumed length if a packet was output, or -1 if no
3676 * packet is output */
3677 int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
3678 const uint8_t *buf, int len)
3679 {
3680 int len1;
3681
3682 len1 = len;
3683 ts->pkt = pkt;
3684 for (;;) {
3685 ts->stop_parse = 0;
3686 if (len < TS_PACKET_SIZE)
3687 return AVERROR_INVALIDDATA;
3688 if (buf[0] != SYNC_BYTE) {
3689 buf++;
3690 len--;
3691 } else {
3692 handle_packet(ts, buf, len1 - len + TS_PACKET_SIZE);
3693 buf += TS_PACKET_SIZE;
3694 len -= TS_PACKET_SIZE;
3695 if (ts->stop_parse == 1)
3696 break;
3697 }
3698 }
3699 return len1 - len;
3700 }
3701
3702 void avpriv_mpegts_parse_close(MpegTSContext *ts)
3703 {
3704 mpegts_free(ts);
3705 av_free(ts);
3706 }
3707
3708 const FFInputFormat ff_mpegts_demuxer = {
3709 .p.name = "mpegts",
3710 .p.long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
3711 .p.flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3712 .p.priv_class = &mpegts_class,
3713 .priv_data_size = sizeof(MpegTSContext),
3714 .read_probe = mpegts_probe,
3715 .read_header = mpegts_read_header,
3716 .read_packet = mpegts_read_packet,
3717 .read_close = mpegts_read_close,
3718 .read_timestamp = mpegts_get_dts,
3719 .flags_internal = FF_INFMT_FLAG_PREFER_CODEC_FRAMERATE,
3720 };
3721
3722 const FFInputFormat ff_mpegtsraw_demuxer = {
3723 .p.name = "mpegtsraw",
3724 .p.long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
3725 .p.flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3726 .p.priv_class = &mpegtsraw_class,
3727 .priv_data_size = sizeof(MpegTSContext),
3728 .read_header = mpegts_read_header,
3729 .read_packet = mpegts_raw_read_packet,
3730 .read_close = mpegts_read_close,
3731 .read_timestamp = mpegts_get_dts,
3732 .flags_internal = FF_INFMT_FLAG_PREFER_CODEC_FRAMERATE,
3733 };
3734