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.

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