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