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.

3400 lines
114KB

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