You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3416 lines
115KB

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