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.

2684 lines
87KB

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