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.

3175 lines
106KB

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