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.

2686 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. int predefined_SLConfigDescriptor_seen;
  1059. } MP4DescrParseContext;
  1060. static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
  1061. const uint8_t *buf, unsigned size,
  1062. Mp4Descr *descr, int max_descr_count)
  1063. {
  1064. int ret;
  1065. if (size > (1 << 30))
  1066. return AVERROR_INVALIDDATA;
  1067. if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
  1068. NULL, NULL, NULL, NULL)) < 0)
  1069. return ret;
  1070. d->s = s;
  1071. d->level = 0;
  1072. d->descr_count = 0;
  1073. d->descr = descr;
  1074. d->active_descr = NULL;
  1075. d->max_descr_count = max_descr_count;
  1076. return 0;
  1077. }
  1078. static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
  1079. {
  1080. int64_t new_off = avio_tell(pb);
  1081. (*len) -= new_off - *off;
  1082. *off = new_off;
  1083. }
  1084. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1085. int target_tag);
  1086. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  1087. {
  1088. while (len > 0) {
  1089. int ret = parse_mp4_descr(d, off, len, 0);
  1090. if (ret < 0)
  1091. return ret;
  1092. update_offsets(&d->pb, &off, &len);
  1093. }
  1094. return 0;
  1095. }
  1096. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1097. {
  1098. avio_rb16(&d->pb); // ID
  1099. avio_r8(&d->pb);
  1100. avio_r8(&d->pb);
  1101. avio_r8(&d->pb);
  1102. avio_r8(&d->pb);
  1103. avio_r8(&d->pb);
  1104. update_offsets(&d->pb, &off, &len);
  1105. return parse_mp4_descr_arr(d, off, len);
  1106. }
  1107. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1108. {
  1109. int id_flags;
  1110. if (len < 2)
  1111. return 0;
  1112. id_flags = avio_rb16(&d->pb);
  1113. if (!(id_flags & 0x0020)) { // URL_Flag
  1114. update_offsets(&d->pb, &off, &len);
  1115. return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
  1116. } else {
  1117. return 0;
  1118. }
  1119. }
  1120. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1121. {
  1122. int es_id = 0;
  1123. if (d->descr_count >= d->max_descr_count)
  1124. return AVERROR_INVALIDDATA;
  1125. ff_mp4_parse_es_descr(&d->pb, &es_id);
  1126. d->active_descr = d->descr + (d->descr_count++);
  1127. d->active_descr->es_id = es_id;
  1128. update_offsets(&d->pb, &off, &len);
  1129. parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  1130. update_offsets(&d->pb, &off, &len);
  1131. if (len > 0)
  1132. parse_mp4_descr(d, off, len, MP4SLDescrTag);
  1133. d->active_descr = NULL;
  1134. return 0;
  1135. }
  1136. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
  1137. int len)
  1138. {
  1139. Mp4Descr *descr = d->active_descr;
  1140. if (!descr)
  1141. return AVERROR_INVALIDDATA;
  1142. d->active_descr->dec_config_descr = av_malloc(len);
  1143. if (!descr->dec_config_descr)
  1144. return AVERROR(ENOMEM);
  1145. descr->dec_config_descr_len = len;
  1146. avio_read(&d->pb, descr->dec_config_descr, len);
  1147. return 0;
  1148. }
  1149. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1150. {
  1151. Mp4Descr *descr = d->active_descr;
  1152. int predefined;
  1153. if (!descr)
  1154. return AVERROR_INVALIDDATA;
  1155. predefined = avio_r8(&d->pb);
  1156. if (!predefined) {
  1157. int lengths;
  1158. int flags = avio_r8(&d->pb);
  1159. descr->sl.use_au_start = !!(flags & 0x80);
  1160. descr->sl.use_au_end = !!(flags & 0x40);
  1161. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  1162. descr->sl.use_padding = !!(flags & 0x08);
  1163. descr->sl.use_timestamps = !!(flags & 0x04);
  1164. descr->sl.use_idle = !!(flags & 0x02);
  1165. descr->sl.timestamp_res = avio_rb32(&d->pb);
  1166. avio_rb32(&d->pb);
  1167. descr->sl.timestamp_len = avio_r8(&d->pb);
  1168. if (descr->sl.timestamp_len > 64) {
  1169. avpriv_request_sample(NULL, "timestamp_len > 64");
  1170. descr->sl.timestamp_len = 64;
  1171. return AVERROR_PATCHWELCOME;
  1172. }
  1173. descr->sl.ocr_len = avio_r8(&d->pb);
  1174. descr->sl.au_len = avio_r8(&d->pb);
  1175. descr->sl.inst_bitrate_len = avio_r8(&d->pb);
  1176. lengths = avio_rb16(&d->pb);
  1177. descr->sl.degr_prior_len = lengths >> 12;
  1178. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  1179. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  1180. } else if (!d->predefined_SLConfigDescriptor_seen){
  1181. avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
  1182. d->predefined_SLConfigDescriptor_seen = 1;
  1183. }
  1184. return 0;
  1185. }
  1186. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1187. int target_tag)
  1188. {
  1189. int tag;
  1190. int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  1191. update_offsets(&d->pb, &off, &len);
  1192. if (len < 0 || len1 > len || len1 <= 0) {
  1193. av_log(d->s, AV_LOG_ERROR,
  1194. "Tag %x length violation new length %d bytes remaining %d\n",
  1195. tag, len1, len);
  1196. return AVERROR_INVALIDDATA;
  1197. }
  1198. if (d->level++ >= MAX_LEVEL) {
  1199. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  1200. goto done;
  1201. }
  1202. if (target_tag && tag != target_tag) {
  1203. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
  1204. target_tag);
  1205. goto done;
  1206. }
  1207. switch (tag) {
  1208. case MP4IODescrTag:
  1209. parse_MP4IODescrTag(d, off, len1);
  1210. break;
  1211. case MP4ODescrTag:
  1212. parse_MP4ODescrTag(d, off, len1);
  1213. break;
  1214. case MP4ESDescrTag:
  1215. parse_MP4ESDescrTag(d, off, len1);
  1216. break;
  1217. case MP4DecConfigDescrTag:
  1218. parse_MP4DecConfigDescrTag(d, off, len1);
  1219. break;
  1220. case MP4SLDescrTag:
  1221. parse_MP4SLDescrTag(d, off, len1);
  1222. break;
  1223. }
  1224. done:
  1225. d->level--;
  1226. avio_seek(&d->pb, off + len1, SEEK_SET);
  1227. return 0;
  1228. }
  1229. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1230. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1231. {
  1232. MP4DescrParseContext d;
  1233. int ret;
  1234. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1235. if (ret < 0)
  1236. return ret;
  1237. ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1238. *descr_count = d.descr_count;
  1239. return ret;
  1240. }
  1241. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1242. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1243. {
  1244. MP4DescrParseContext d;
  1245. int ret;
  1246. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1247. if (ret < 0)
  1248. return ret;
  1249. ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1250. *descr_count = d.descr_count;
  1251. return ret;
  1252. }
  1253. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
  1254. int section_len)
  1255. {
  1256. MpegTSContext *ts = filter->u.section_filter.opaque;
  1257. SectionHeader h;
  1258. const uint8_t *p, *p_end;
  1259. AVIOContext pb;
  1260. int mp4_descr_count = 0;
  1261. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1262. int i, pid;
  1263. AVFormatContext *s = ts->stream;
  1264. p_end = section + section_len - 4;
  1265. p = section;
  1266. if (parse_section_header(&h, &p, p_end) < 0)
  1267. return;
  1268. if (h.tid != M4OD_TID)
  1269. return;
  1270. mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
  1271. MAX_MP4_DESCR_COUNT);
  1272. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1273. if (!ts->pids[pid])
  1274. continue;
  1275. for (i = 0; i < mp4_descr_count; i++) {
  1276. PESContext *pes;
  1277. AVStream *st;
  1278. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1279. continue;
  1280. if (ts->pids[pid]->type != MPEGTS_PES) {
  1281. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1282. continue;
  1283. }
  1284. pes = ts->pids[pid]->u.pes_filter.opaque;
  1285. st = pes->st;
  1286. if (!st)
  1287. continue;
  1288. pes->sl = mp4_descr[i].sl;
  1289. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1290. mp4_descr[i].dec_config_descr_len, 0,
  1291. NULL, NULL, NULL, NULL);
  1292. ff_mp4_read_dec_config_descr(s, st, &pb);
  1293. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1294. st->codec->extradata_size > 0)
  1295. st->need_parsing = 0;
  1296. if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1297. st->codec->extradata_size > 0)
  1298. st->need_parsing = 0;
  1299. if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1300. // do nothing
  1301. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO)
  1302. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1303. else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
  1304. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1305. else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
  1306. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1307. }
  1308. }
  1309. for (i = 0; i < mp4_descr_count; i++)
  1310. av_free(mp4_descr[i].dec_config_descr);
  1311. }
  1312. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1313. const uint8_t **pp, const uint8_t *desc_list_end,
  1314. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1315. MpegTSContext *ts)
  1316. {
  1317. const uint8_t *desc_end;
  1318. int desc_len, desc_tag, desc_es_id;
  1319. char language[252];
  1320. int i;
  1321. desc_tag = get8(pp, desc_list_end);
  1322. if (desc_tag < 0)
  1323. return AVERROR_INVALIDDATA;
  1324. desc_len = get8(pp, desc_list_end);
  1325. if (desc_len < 0)
  1326. return AVERROR_INVALIDDATA;
  1327. desc_end = *pp + desc_len;
  1328. if (desc_end > desc_list_end)
  1329. return AVERROR_INVALIDDATA;
  1330. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1331. if (st->codec->codec_id == AV_CODEC_ID_NONE &&
  1332. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1333. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1334. switch (desc_tag) {
  1335. case 0x1E: /* SL descriptor */
  1336. desc_es_id = get16(pp, desc_end);
  1337. if (ts && ts->pids[pid])
  1338. ts->pids[pid]->es_id = desc_es_id;
  1339. for (i = 0; i < mp4_descr_count; i++)
  1340. if (mp4_descr[i].dec_config_descr_len &&
  1341. mp4_descr[i].es_id == desc_es_id) {
  1342. AVIOContext pb;
  1343. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1344. mp4_descr[i].dec_config_descr_len, 0,
  1345. NULL, NULL, NULL, NULL);
  1346. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1347. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1348. st->codec->extradata_size > 0)
  1349. st->need_parsing = 0;
  1350. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1351. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1352. }
  1353. break;
  1354. case 0x1F: /* FMC descriptor */
  1355. get16(pp, desc_end);
  1356. if (mp4_descr_count > 0 &&
  1357. (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe > 0) &&
  1358. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1359. AVIOContext pb;
  1360. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1361. mp4_descr->dec_config_descr_len, 0,
  1362. NULL, NULL, NULL, NULL);
  1363. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1364. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1365. st->codec->extradata_size > 0) {
  1366. st->request_probe = st->need_parsing = 0;
  1367. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1368. }
  1369. }
  1370. break;
  1371. case 0x56: /* DVB teletext descriptor */
  1372. {
  1373. uint8_t *extradata = NULL;
  1374. int language_count = desc_len / 5;
  1375. if (desc_len > 0 && desc_len % 5 != 0)
  1376. return AVERROR_INVALIDDATA;
  1377. if (language_count > 0) {
  1378. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1379. if (language_count > sizeof(language) / 4) {
  1380. language_count = sizeof(language) / 4;
  1381. }
  1382. if (st->codec->extradata == NULL) {
  1383. if (ff_alloc_extradata(st->codec, language_count * 2)) {
  1384. return AVERROR(ENOMEM);
  1385. }
  1386. }
  1387. if (st->codec->extradata_size < language_count * 2)
  1388. return AVERROR_INVALIDDATA;
  1389. extradata = st->codec->extradata;
  1390. for (i = 0; i < language_count; i++) {
  1391. language[i * 4 + 0] = get8(pp, desc_end);
  1392. language[i * 4 + 1] = get8(pp, desc_end);
  1393. language[i * 4 + 2] = get8(pp, desc_end);
  1394. language[i * 4 + 3] = ',';
  1395. memcpy(extradata, *pp, 2);
  1396. extradata += 2;
  1397. *pp += 2;
  1398. }
  1399. language[i * 4 - 1] = 0;
  1400. av_dict_set(&st->metadata, "language", language, 0);
  1401. }
  1402. }
  1403. break;
  1404. case 0x59: /* subtitling descriptor */
  1405. {
  1406. /* 8 bytes per DVB subtitle substream data:
  1407. * ISO_639_language_code (3 bytes),
  1408. * subtitling_type (1 byte),
  1409. * composition_page_id (2 bytes),
  1410. * ancillary_page_id (2 bytes) */
  1411. int language_count = desc_len / 8;
  1412. if (desc_len > 0 && desc_len % 8 != 0)
  1413. return AVERROR_INVALIDDATA;
  1414. if (language_count > 1) {
  1415. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1416. }
  1417. if (language_count > 0) {
  1418. uint8_t *extradata;
  1419. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1420. if (language_count > sizeof(language) / 4) {
  1421. language_count = sizeof(language) / 4;
  1422. }
  1423. if (st->codec->extradata == NULL) {
  1424. if (ff_alloc_extradata(st->codec, language_count * 5)) {
  1425. return AVERROR(ENOMEM);
  1426. }
  1427. }
  1428. if (st->codec->extradata_size < language_count * 5)
  1429. return AVERROR_INVALIDDATA;
  1430. extradata = st->codec->extradata;
  1431. for (i = 0; i < language_count; i++) {
  1432. language[i * 4 + 0] = get8(pp, desc_end);
  1433. language[i * 4 + 1] = get8(pp, desc_end);
  1434. language[i * 4 + 2] = get8(pp, desc_end);
  1435. language[i * 4 + 3] = ',';
  1436. /* hearing impaired subtitles detection using subtitling_type */
  1437. switch (*pp[0]) {
  1438. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1439. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1440. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1441. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1442. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1443. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1444. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1445. break;
  1446. }
  1447. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1448. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1449. extradata += 5;
  1450. *pp += 4;
  1451. }
  1452. language[i * 4 - 1] = 0;
  1453. av_dict_set(&st->metadata, "language", language, 0);
  1454. }
  1455. }
  1456. break;
  1457. case 0x0a: /* ISO 639 language descriptor */
  1458. for (i = 0; i + 4 <= desc_len; i += 4) {
  1459. language[i + 0] = get8(pp, desc_end);
  1460. language[i + 1] = get8(pp, desc_end);
  1461. language[i + 2] = get8(pp, desc_end);
  1462. language[i + 3] = ',';
  1463. switch (get8(pp, desc_end)) {
  1464. case 0x01:
  1465. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1466. break;
  1467. case 0x02:
  1468. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1469. break;
  1470. case 0x03:
  1471. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1472. break;
  1473. }
  1474. }
  1475. if (i) {
  1476. language[i - 1] = 0;
  1477. av_dict_set(&st->metadata, "language", language, 0);
  1478. }
  1479. break;
  1480. case 0x05: /* registration descriptor */
  1481. st->codec->codec_tag = bytestream_get_le32(pp);
  1482. av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
  1483. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1484. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1485. break;
  1486. case 0x52: /* stream identifier descriptor */
  1487. st->stream_identifier = 1 + get8(pp, desc_end);
  1488. break;
  1489. case 0x26: /* metadata descriptor */
  1490. if (get16(pp, desc_end) == 0xFFFF)
  1491. *pp += 4;
  1492. if (get8(pp, desc_end) == 0xFF) {
  1493. st->codec->codec_tag = bytestream_get_le32(pp);
  1494. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1495. mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
  1496. }
  1497. break;
  1498. default:
  1499. break;
  1500. }
  1501. *pp = desc_end;
  1502. return 0;
  1503. }
  1504. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1505. {
  1506. MpegTSContext *ts = filter->u.section_filter.opaque;
  1507. SectionHeader h1, *h = &h1;
  1508. PESContext *pes;
  1509. AVStream *st;
  1510. const uint8_t *p, *p_end, *desc_list_end;
  1511. int program_info_length, pcr_pid, pid, stream_type;
  1512. int desc_list_len;
  1513. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1514. int mp4_descr_count = 0;
  1515. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1516. int i;
  1517. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1518. hex_dump_debug(ts->stream, section, section_len);
  1519. p_end = section + section_len - 4;
  1520. p = section;
  1521. if (parse_section_header(h, &p, p_end) < 0)
  1522. return;
  1523. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1524. h->id, h->sec_num, h->last_sec_num);
  1525. if (h->tid != PMT_TID)
  1526. return;
  1527. clear_program(ts, h->id);
  1528. pcr_pid = get16(&p, p_end);
  1529. if (pcr_pid < 0)
  1530. return;
  1531. pcr_pid &= 0x1fff;
  1532. add_pid_to_pmt(ts, h->id, pcr_pid);
  1533. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1534. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1535. program_info_length = get16(&p, p_end);
  1536. if (program_info_length < 0)
  1537. return;
  1538. program_info_length &= 0xfff;
  1539. while (program_info_length >= 2) {
  1540. uint8_t tag, len;
  1541. tag = get8(&p, p_end);
  1542. len = get8(&p, p_end);
  1543. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1544. if (len > program_info_length - 2)
  1545. // something else is broken, exit the program_descriptors_loop
  1546. break;
  1547. program_info_length -= len + 2;
  1548. if (tag == 0x1d) { // IOD descriptor
  1549. get8(&p, p_end); // scope
  1550. get8(&p, p_end); // label
  1551. len -= 2;
  1552. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1553. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1554. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1555. prog_reg_desc = bytestream_get_le32(&p);
  1556. len -= 4;
  1557. }
  1558. p += len;
  1559. }
  1560. p += program_info_length;
  1561. if (p >= p_end)
  1562. goto out;
  1563. // stop parsing after pmt, we found header
  1564. if (!ts->stream->nb_streams)
  1565. ts->stop_parse = 2;
  1566. set_pmt_found(ts, h->id);
  1567. for (;;) {
  1568. st = 0;
  1569. pes = NULL;
  1570. stream_type = get8(&p, p_end);
  1571. if (stream_type < 0)
  1572. break;
  1573. pid = get16(&p, p_end);
  1574. if (pid < 0)
  1575. goto out;
  1576. pid &= 0x1fff;
  1577. if (pid == ts->current_pid)
  1578. goto out;
  1579. /* now create stream */
  1580. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1581. pes = ts->pids[pid]->u.pes_filter.opaque;
  1582. if (!pes->st) {
  1583. pes->st = avformat_new_stream(pes->stream, NULL);
  1584. if (!pes->st)
  1585. goto out;
  1586. pes->st->id = pes->pid;
  1587. }
  1588. st = pes->st;
  1589. } else if (stream_type != 0x13) {
  1590. if (ts->pids[pid])
  1591. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1592. pes = add_pes_stream(ts, pid, pcr_pid);
  1593. if (pes) {
  1594. st = avformat_new_stream(pes->stream, NULL);
  1595. if (!st)
  1596. goto out;
  1597. st->id = pes->pid;
  1598. }
  1599. } else {
  1600. int idx = ff_find_stream_index(ts->stream, pid);
  1601. if (idx >= 0) {
  1602. st = ts->stream->streams[idx];
  1603. } else {
  1604. st = avformat_new_stream(ts->stream, NULL);
  1605. if (!st)
  1606. goto out;
  1607. st->id = pid;
  1608. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1609. }
  1610. }
  1611. if (!st)
  1612. goto out;
  1613. if (pes && !pes->stream_type)
  1614. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1615. add_pid_to_pmt(ts, h->id, pid);
  1616. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1617. desc_list_len = get16(&p, p_end);
  1618. if (desc_list_len < 0)
  1619. goto out;
  1620. desc_list_len &= 0xfff;
  1621. desc_list_end = p + desc_list_len;
  1622. if (desc_list_end > p_end)
  1623. goto out;
  1624. for (;;) {
  1625. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1626. desc_list_end, mp4_descr,
  1627. mp4_descr_count, pid, ts) < 0)
  1628. break;
  1629. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1630. stream_type == 0x83 && pes->sub_st) {
  1631. ff_program_add_stream_index(ts->stream, h->id,
  1632. pes->sub_st->index);
  1633. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1634. }
  1635. }
  1636. p = desc_list_end;
  1637. }
  1638. if (!ts->pids[pcr_pid])
  1639. mpegts_open_pcr_filter(ts, pcr_pid);
  1640. out:
  1641. for (i = 0; i < mp4_descr_count; i++)
  1642. av_free(mp4_descr[i].dec_config_descr);
  1643. }
  1644. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1645. {
  1646. MpegTSContext *ts = filter->u.section_filter.opaque;
  1647. SectionHeader h1, *h = &h1;
  1648. const uint8_t *p, *p_end;
  1649. int sid, pmt_pid;
  1650. AVProgram *program;
  1651. av_dlog(ts->stream, "PAT:\n");
  1652. hex_dump_debug(ts->stream, section, section_len);
  1653. p_end = section + section_len - 4;
  1654. p = section;
  1655. if (parse_section_header(h, &p, p_end) < 0)
  1656. return;
  1657. if (h->tid != PAT_TID)
  1658. return;
  1659. ts->stream->ts_id = h->id;
  1660. clear_programs(ts);
  1661. for (;;) {
  1662. sid = get16(&p, p_end);
  1663. if (sid < 0)
  1664. break;
  1665. pmt_pid = get16(&p, p_end);
  1666. if (pmt_pid < 0)
  1667. break;
  1668. pmt_pid &= 0x1fff;
  1669. if (pmt_pid == ts->current_pid)
  1670. break;
  1671. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1672. if (sid == 0x0000) {
  1673. /* NIT info */
  1674. } else {
  1675. MpegTSFilter *fil = ts->pids[pmt_pid];
  1676. program = av_new_program(ts->stream, sid);
  1677. program->program_num = sid;
  1678. program->pmt_pid = pmt_pid;
  1679. if (fil)
  1680. if ( fil->type != MPEGTS_SECTION
  1681. || fil->pid != pmt_pid
  1682. || fil->u.section_filter.section_cb != pmt_cb)
  1683. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1684. if (!ts->pids[pmt_pid])
  1685. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1686. add_pat_entry(ts, sid);
  1687. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1688. add_pid_to_pmt(ts, sid, pmt_pid);
  1689. }
  1690. }
  1691. if (sid < 0) {
  1692. int i,j;
  1693. for (j=0; j<ts->stream->nb_programs; j++) {
  1694. for (i = 0; i < ts->nb_prg; i++)
  1695. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1696. break;
  1697. if (i==ts->nb_prg)
  1698. clear_avprogram(ts, ts->stream->programs[j]->id);
  1699. }
  1700. }
  1701. }
  1702. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1703. {
  1704. MpegTSContext *ts = filter->u.section_filter.opaque;
  1705. SectionHeader h1, *h = &h1;
  1706. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1707. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1708. char *name, *provider_name;
  1709. av_dlog(ts->stream, "SDT:\n");
  1710. hex_dump_debug(ts->stream, section, section_len);
  1711. p_end = section + section_len - 4;
  1712. p = section;
  1713. if (parse_section_header(h, &p, p_end) < 0)
  1714. return;
  1715. if (h->tid != SDT_TID)
  1716. return;
  1717. onid = get16(&p, p_end);
  1718. if (onid < 0)
  1719. return;
  1720. val = get8(&p, p_end);
  1721. if (val < 0)
  1722. return;
  1723. for (;;) {
  1724. sid = get16(&p, p_end);
  1725. if (sid < 0)
  1726. break;
  1727. val = get8(&p, p_end);
  1728. if (val < 0)
  1729. break;
  1730. desc_list_len = get16(&p, p_end);
  1731. if (desc_list_len < 0)
  1732. break;
  1733. desc_list_len &= 0xfff;
  1734. desc_list_end = p + desc_list_len;
  1735. if (desc_list_end > p_end)
  1736. break;
  1737. for (;;) {
  1738. desc_tag = get8(&p, desc_list_end);
  1739. if (desc_tag < 0)
  1740. break;
  1741. desc_len = get8(&p, desc_list_end);
  1742. desc_end = p + desc_len;
  1743. if (desc_end > desc_list_end)
  1744. break;
  1745. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1746. desc_tag, desc_len);
  1747. switch (desc_tag) {
  1748. case 0x48:
  1749. service_type = get8(&p, p_end);
  1750. if (service_type < 0)
  1751. break;
  1752. provider_name = getstr8(&p, p_end);
  1753. if (!provider_name)
  1754. break;
  1755. name = getstr8(&p, p_end);
  1756. if (name) {
  1757. AVProgram *program = av_new_program(ts->stream, sid);
  1758. if (program) {
  1759. av_dict_set(&program->metadata, "service_name", name, 0);
  1760. av_dict_set(&program->metadata, "service_provider",
  1761. provider_name, 0);
  1762. }
  1763. }
  1764. av_free(name);
  1765. av_free(provider_name);
  1766. break;
  1767. default:
  1768. break;
  1769. }
  1770. p = desc_end;
  1771. }
  1772. p = desc_list_end;
  1773. }
  1774. }
  1775. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1776. const uint8_t *packet);
  1777. /* handle one TS packet */
  1778. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1779. {
  1780. AVFormatContext *s = ts->stream;
  1781. MpegTSFilter *tss;
  1782. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1783. has_adaptation, has_payload;
  1784. const uint8_t *p, *p_end;
  1785. int64_t pos;
  1786. pid = AV_RB16(packet + 1) & 0x1fff;
  1787. if (pid && discard_pid(ts, pid))
  1788. return 0;
  1789. is_start = packet[1] & 0x40;
  1790. tss = ts->pids[pid];
  1791. if (ts->auto_guess && tss == NULL && is_start) {
  1792. add_pes_stream(ts, pid, -1);
  1793. tss = ts->pids[pid];
  1794. }
  1795. if (!tss)
  1796. return 0;
  1797. ts->current_pid = pid;
  1798. afc = (packet[3] >> 4) & 3;
  1799. if (afc == 0) /* reserved value */
  1800. return 0;
  1801. has_adaptation = afc & 2;
  1802. has_payload = afc & 1;
  1803. is_discontinuity = has_adaptation &&
  1804. packet[4] != 0 && /* with length > 0 */
  1805. (packet[5] & 0x80); /* and discontinuity indicated */
  1806. /* continuity check (currently not used) */
  1807. cc = (packet[3] & 0xf);
  1808. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1809. cc_ok = pid == 0x1FFF || // null packet PID
  1810. is_discontinuity ||
  1811. tss->last_cc < 0 ||
  1812. expected_cc == cc;
  1813. tss->last_cc = cc;
  1814. if (!cc_ok) {
  1815. av_log(ts->stream, AV_LOG_DEBUG,
  1816. "Continuity check failed for pid %d expected %d got %d\n",
  1817. pid, expected_cc, cc);
  1818. if (tss->type == MPEGTS_PES) {
  1819. PESContext *pc = tss->u.pes_filter.opaque;
  1820. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1821. }
  1822. }
  1823. if (!has_payload && tss->type != MPEGTS_PCR)
  1824. return 0;
  1825. p = packet + 4;
  1826. if (has_adaptation) {
  1827. /* skip adaptation field */
  1828. p += p[0] + 1;
  1829. }
  1830. /* if past the end of packet, ignore */
  1831. p_end = packet + TS_PACKET_SIZE;
  1832. if (p > p_end || (p == p_end && tss->type != MPEGTS_PCR))
  1833. return 0;
  1834. pos = avio_tell(ts->stream->pb);
  1835. if (pos >= 0) {
  1836. av_assert0(pos >= TS_PACKET_SIZE);
  1837. ts->pos47_full = pos - TS_PACKET_SIZE;
  1838. }
  1839. if (tss->type == MPEGTS_SECTION) {
  1840. if (is_start) {
  1841. /* pointer field present */
  1842. len = *p++;
  1843. if (p + len > p_end)
  1844. return 0;
  1845. if (len && cc_ok) {
  1846. /* write remaining section bytes */
  1847. write_section_data(s, tss,
  1848. p, len, 0);
  1849. /* check whether filter has been closed */
  1850. if (!ts->pids[pid])
  1851. return 0;
  1852. }
  1853. p += len;
  1854. if (p < p_end) {
  1855. write_section_data(s, tss,
  1856. p, p_end - p, 1);
  1857. }
  1858. } else {
  1859. if (cc_ok) {
  1860. write_section_data(s, tss,
  1861. p, p_end - p, 0);
  1862. }
  1863. }
  1864. // stop find_stream_info from waiting for more streams
  1865. // when all programs have received a PMT
  1866. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER) {
  1867. int i;
  1868. for (i = 0; i < ts->nb_prg; i++) {
  1869. if (!ts->prg[i].pmt_found)
  1870. break;
  1871. }
  1872. if (i == ts->nb_prg && ts->nb_prg > 0) {
  1873. if (ts->stream->nb_streams > 1 || pos > 100000) {
  1874. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  1875. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1876. }
  1877. }
  1878. }
  1879. } else {
  1880. int ret;
  1881. int64_t pcr_h;
  1882. int pcr_l;
  1883. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1884. tss->last_pcr = pcr_h * 300 + pcr_l;
  1885. // Note: The position here points actually behind the current packet.
  1886. if (tss->type == MPEGTS_PES) {
  1887. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1888. pos - ts->raw_packet_size)) < 0)
  1889. return ret;
  1890. }
  1891. }
  1892. return 0;
  1893. }
  1894. static void reanalyze(MpegTSContext *ts) {
  1895. AVIOContext *pb = ts->stream->pb;
  1896. int64_t pos = avio_tell(pb);
  1897. if (pos < 0)
  1898. return;
  1899. pos -= ts->pos47_full;
  1900. if (pos == TS_PACKET_SIZE) {
  1901. ts->size_stat[0] ++;
  1902. } else if (pos == TS_DVHS_PACKET_SIZE) {
  1903. ts->size_stat[1] ++;
  1904. } else if (pos == TS_FEC_PACKET_SIZE) {
  1905. ts->size_stat[2] ++;
  1906. }
  1907. ts->size_stat_count ++;
  1908. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  1909. int newsize = 0;
  1910. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  1911. newsize = TS_PACKET_SIZE;
  1912. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  1913. newsize = TS_DVHS_PACKET_SIZE;
  1914. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  1915. newsize = TS_FEC_PACKET_SIZE;
  1916. }
  1917. if (newsize && newsize != ts->raw_packet_size) {
  1918. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  1919. ts->raw_packet_size = newsize;
  1920. }
  1921. ts->size_stat_count = 0;
  1922. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  1923. }
  1924. }
  1925. /* XXX: try to find a better synchro over several packets (use
  1926. * get_packet_size() ?) */
  1927. static int mpegts_resync(AVFormatContext *s)
  1928. {
  1929. AVIOContext *pb = s->pb;
  1930. int c, i;
  1931. for (i = 0; i < MAX_RESYNC_SIZE; i++) {
  1932. c = avio_r8(pb);
  1933. if (url_feof(pb))
  1934. return AVERROR_EOF;
  1935. if (c == 0x47) {
  1936. avio_seek(pb, -1, SEEK_CUR);
  1937. reanalyze(s->priv_data);
  1938. return 0;
  1939. }
  1940. }
  1941. av_log(s, AV_LOG_ERROR,
  1942. "max resync size reached, could not find sync byte\n");
  1943. /* no sync found */
  1944. return AVERROR_INVALIDDATA;
  1945. }
  1946. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  1947. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  1948. const uint8_t **data)
  1949. {
  1950. AVIOContext *pb = s->pb;
  1951. int len;
  1952. for (;;) {
  1953. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  1954. if (len != TS_PACKET_SIZE)
  1955. return len < 0 ? len : AVERROR_EOF;
  1956. /* check packet sync byte */
  1957. if ((*data)[0] != 0x47) {
  1958. /* find a new packet start */
  1959. uint64_t pos = avio_tell(pb);
  1960. avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
  1961. if (mpegts_resync(s) < 0)
  1962. return AVERROR(EAGAIN);
  1963. else
  1964. continue;
  1965. } else {
  1966. break;
  1967. }
  1968. }
  1969. return 0;
  1970. }
  1971. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  1972. {
  1973. AVIOContext *pb = s->pb;
  1974. int skip = raw_packet_size - TS_PACKET_SIZE;
  1975. if (skip > 0)
  1976. avio_skip(pb, skip);
  1977. }
  1978. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1979. {
  1980. AVFormatContext *s = ts->stream;
  1981. uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  1982. const uint8_t *data;
  1983. int packet_num, ret = 0;
  1984. if (avio_tell(s->pb) != ts->last_pos) {
  1985. int i;
  1986. av_dlog(ts->stream, "Skipping after seek\n");
  1987. /* seek detected, flush pes buffer */
  1988. for (i = 0; i < NB_PID_MAX; i++) {
  1989. if (ts->pids[i]) {
  1990. if (ts->pids[i]->type == MPEGTS_PES) {
  1991. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1992. av_buffer_unref(&pes->buffer);
  1993. pes->data_index = 0;
  1994. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1995. }
  1996. ts->pids[i]->last_cc = -1;
  1997. ts->pids[i]->last_pcr = -1;
  1998. }
  1999. }
  2000. }
  2001. ts->stop_parse = 0;
  2002. packet_num = 0;
  2003. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2004. for (;;) {
  2005. packet_num++;
  2006. if (nb_packets != 0 && packet_num >= nb_packets ||
  2007. ts->stop_parse > 1) {
  2008. ret = AVERROR(EAGAIN);
  2009. break;
  2010. }
  2011. if (ts->stop_parse > 0)
  2012. break;
  2013. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2014. if (ret != 0)
  2015. break;
  2016. ret = handle_packet(ts, data);
  2017. finished_reading_packet(s, ts->raw_packet_size);
  2018. if (ret != 0)
  2019. break;
  2020. }
  2021. ts->last_pos = avio_tell(s->pb);
  2022. return ret;
  2023. }
  2024. static int mpegts_probe(AVProbeData *p)
  2025. {
  2026. const int size = p->buf_size;
  2027. int maxscore = 0;
  2028. int sumscore = 0;
  2029. int i;
  2030. int check_count = size / TS_FEC_PACKET_SIZE;
  2031. #define CHECK_COUNT 10
  2032. #define CHECK_BLOCK 100
  2033. if (check_count < CHECK_COUNT)
  2034. return AVERROR_INVALIDDATA;
  2035. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2036. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2037. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
  2038. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  2039. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  2040. score = FFMAX3(score, dvhs_score, fec_score);
  2041. sumscore += score;
  2042. maxscore = FFMAX(maxscore, score);
  2043. }
  2044. sumscore = sumscore * CHECK_COUNT / check_count;
  2045. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2046. av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2047. if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2048. else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2049. else
  2050. return AVERROR_INVALIDDATA;
  2051. }
  2052. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2053. * (-1) if not available */
  2054. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2055. {
  2056. int afc, len, flags;
  2057. const uint8_t *p;
  2058. unsigned int v;
  2059. afc = (packet[3] >> 4) & 3;
  2060. if (afc <= 1)
  2061. return AVERROR_INVALIDDATA;
  2062. p = packet + 4;
  2063. len = p[0];
  2064. p++;
  2065. if (len == 0)
  2066. return AVERROR_INVALIDDATA;
  2067. flags = *p++;
  2068. len--;
  2069. if (!(flags & 0x10))
  2070. return AVERROR_INVALIDDATA;
  2071. if (len < 6)
  2072. return AVERROR_INVALIDDATA;
  2073. v = AV_RB32(p);
  2074. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2075. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2076. return 0;
  2077. }
  2078. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2079. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2080. * probe buffer usually is big enough. Only warn if the seek failed
  2081. * on files where the seek should work. */
  2082. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2083. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2084. }
  2085. static int mpegts_read_header(AVFormatContext *s)
  2086. {
  2087. MpegTSContext *ts = s->priv_data;
  2088. AVIOContext *pb = s->pb;
  2089. uint8_t buf[8 * 1024] = {0};
  2090. int len;
  2091. int64_t pos;
  2092. ffio_ensure_seekback(pb, s->probesize);
  2093. /* read the first 8192 bytes to get packet size */
  2094. pos = avio_tell(pb);
  2095. len = avio_read(pb, buf, sizeof(buf));
  2096. ts->raw_packet_size = get_packet_size(buf, len);
  2097. if (ts->raw_packet_size <= 0) {
  2098. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2099. ts->raw_packet_size = TS_PACKET_SIZE;
  2100. }
  2101. ts->stream = s;
  2102. ts->auto_guess = 0;
  2103. if (s->iformat == &ff_mpegts_demuxer) {
  2104. /* normal demux */
  2105. /* first do a scan to get all the services */
  2106. seek_back(s, pb, pos);
  2107. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2108. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2109. handle_packets(ts, s->probesize / ts->raw_packet_size);
  2110. /* if could not find service, enable auto_guess */
  2111. ts->auto_guess = 1;
  2112. av_dlog(ts->stream, "tuning done\n");
  2113. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2114. } else {
  2115. AVStream *st;
  2116. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2117. int64_t pcrs[2], pcr_h;
  2118. int packet_count[2];
  2119. uint8_t packet[TS_PACKET_SIZE];
  2120. const uint8_t *data;
  2121. /* only read packets */
  2122. st = avformat_new_stream(s, NULL);
  2123. if (!st)
  2124. return AVERROR(ENOMEM);
  2125. avpriv_set_pts_info(st, 60, 1, 27000000);
  2126. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2127. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  2128. /* we iterate until we find two PCRs to estimate the bitrate */
  2129. pcr_pid = -1;
  2130. nb_pcrs = 0;
  2131. nb_packets = 0;
  2132. for (;;) {
  2133. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2134. if (ret < 0)
  2135. return ret;
  2136. pid = AV_RB16(data + 1) & 0x1fff;
  2137. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2138. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2139. finished_reading_packet(s, ts->raw_packet_size);
  2140. pcr_pid = pid;
  2141. packet_count[nb_pcrs] = nb_packets;
  2142. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2143. nb_pcrs++;
  2144. if (nb_pcrs >= 2)
  2145. break;
  2146. } else {
  2147. finished_reading_packet(s, ts->raw_packet_size);
  2148. }
  2149. nb_packets++;
  2150. }
  2151. /* NOTE1: the bitrate is computed without the FEC */
  2152. /* NOTE2: it is only the bitrate of the start of the stream */
  2153. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2154. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2155. s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
  2156. st->codec->bit_rate = s->bit_rate;
  2157. st->start_time = ts->cur_pcr;
  2158. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  2159. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2160. }
  2161. seek_back(s, pb, pos);
  2162. return 0;
  2163. }
  2164. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2165. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2166. {
  2167. MpegTSContext *ts = s->priv_data;
  2168. int ret, i;
  2169. int64_t pcr_h, next_pcr_h, pos;
  2170. int pcr_l, next_pcr_l;
  2171. uint8_t pcr_buf[12];
  2172. const uint8_t *data;
  2173. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2174. return AVERROR(ENOMEM);
  2175. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2176. pkt->pos = avio_tell(s->pb);
  2177. if (ret < 0) {
  2178. av_free_packet(pkt);
  2179. return ret;
  2180. }
  2181. if (data != pkt->data)
  2182. memcpy(pkt->data, data, ts->raw_packet_size);
  2183. finished_reading_packet(s, ts->raw_packet_size);
  2184. if (ts->mpeg2ts_compute_pcr) {
  2185. /* compute exact PCR for each packet */
  2186. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2187. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2188. pos = avio_tell(s->pb);
  2189. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2190. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2191. avio_read(s->pb, pcr_buf, 12);
  2192. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2193. /* XXX: not precise enough */
  2194. ts->pcr_incr =
  2195. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2196. (i + 1);
  2197. break;
  2198. }
  2199. }
  2200. avio_seek(s->pb, pos, SEEK_SET);
  2201. /* no next PCR found: we use previous increment */
  2202. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2203. }
  2204. pkt->pts = ts->cur_pcr;
  2205. pkt->duration = ts->pcr_incr;
  2206. ts->cur_pcr += ts->pcr_incr;
  2207. }
  2208. pkt->stream_index = 0;
  2209. return 0;
  2210. }
  2211. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2212. {
  2213. MpegTSContext *ts = s->priv_data;
  2214. int ret, i;
  2215. pkt->size = -1;
  2216. ts->pkt = pkt;
  2217. ret = handle_packets(ts, 0);
  2218. if (ret < 0) {
  2219. av_free_packet(ts->pkt);
  2220. /* flush pes data left */
  2221. for (i = 0; i < NB_PID_MAX; i++)
  2222. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2223. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2224. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2225. new_pes_packet(pes, pkt);
  2226. pes->state = MPEGTS_SKIP;
  2227. ret = 0;
  2228. break;
  2229. }
  2230. }
  2231. }
  2232. if (!ret && pkt->size < 0)
  2233. ret = AVERROR(EINTR);
  2234. return ret;
  2235. }
  2236. static void mpegts_free(MpegTSContext *ts)
  2237. {
  2238. int i;
  2239. clear_programs(ts);
  2240. for (i = 0; i < NB_PID_MAX; i++)
  2241. if (ts->pids[i])
  2242. mpegts_close_filter(ts, ts->pids[i]);
  2243. }
  2244. static int mpegts_read_close(AVFormatContext *s)
  2245. {
  2246. MpegTSContext *ts = s->priv_data;
  2247. mpegts_free(ts);
  2248. return 0;
  2249. }
  2250. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2251. int64_t *ppos, int64_t pos_limit)
  2252. {
  2253. MpegTSContext *ts = s->priv_data;
  2254. int64_t pos, timestamp;
  2255. uint8_t buf[TS_PACKET_SIZE];
  2256. int pcr_l, pcr_pid =
  2257. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2258. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2259. pos =
  2260. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2261. ts->raw_packet_size + pos47;
  2262. while(pos < pos_limit) {
  2263. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2264. return AV_NOPTS_VALUE;
  2265. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2266. return AV_NOPTS_VALUE;
  2267. if (buf[0] != 0x47) {
  2268. avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
  2269. if (mpegts_resync(s) < 0)
  2270. return AV_NOPTS_VALUE;
  2271. pos = avio_tell(s->pb);
  2272. continue;
  2273. }
  2274. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2275. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2276. *ppos = pos;
  2277. return timestamp;
  2278. }
  2279. pos += ts->raw_packet_size;
  2280. }
  2281. return AV_NOPTS_VALUE;
  2282. }
  2283. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2284. int64_t *ppos, int64_t pos_limit)
  2285. {
  2286. MpegTSContext *ts = s->priv_data;
  2287. int64_t pos;
  2288. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2289. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2290. ff_read_frame_flush(s);
  2291. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2292. return AV_NOPTS_VALUE;
  2293. while(pos < pos_limit) {
  2294. int ret;
  2295. AVPacket pkt;
  2296. av_init_packet(&pkt);
  2297. ret = av_read_frame(s, &pkt);
  2298. if (ret < 0)
  2299. return AV_NOPTS_VALUE;
  2300. av_free_packet(&pkt);
  2301. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2302. ff_reduce_index(s, pkt.stream_index);
  2303. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2304. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2305. *ppos = pkt.pos;
  2306. return pkt.dts;
  2307. }
  2308. }
  2309. pos = pkt.pos;
  2310. }
  2311. return AV_NOPTS_VALUE;
  2312. }
  2313. /**************************************************************/
  2314. /* parsing functions - called from other demuxers such as RTP */
  2315. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  2316. {
  2317. MpegTSContext *ts;
  2318. ts = av_mallocz(sizeof(MpegTSContext));
  2319. if (!ts)
  2320. return NULL;
  2321. /* no stream case, currently used by RTP */
  2322. ts->raw_packet_size = TS_PACKET_SIZE;
  2323. ts->stream = s;
  2324. ts->auto_guess = 1;
  2325. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2326. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2327. return ts;
  2328. }
  2329. /* return the consumed length if a packet was output, or -1 if no
  2330. * packet is output */
  2331. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2332. const uint8_t *buf, int len)
  2333. {
  2334. int len1;
  2335. len1 = len;
  2336. ts->pkt = pkt;
  2337. for (;;) {
  2338. ts->stop_parse = 0;
  2339. if (len < TS_PACKET_SIZE)
  2340. return AVERROR_INVALIDDATA;
  2341. if (buf[0] != 0x47) {
  2342. buf++;
  2343. len--;
  2344. } else {
  2345. handle_packet(ts, buf);
  2346. buf += TS_PACKET_SIZE;
  2347. len -= TS_PACKET_SIZE;
  2348. if (ts->stop_parse == 1)
  2349. break;
  2350. }
  2351. }
  2352. return len1 - len;
  2353. }
  2354. void ff_mpegts_parse_close(MpegTSContext *ts)
  2355. {
  2356. mpegts_free(ts);
  2357. av_free(ts);
  2358. }
  2359. AVInputFormat ff_mpegts_demuxer = {
  2360. .name = "mpegts",
  2361. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2362. .priv_data_size = sizeof(MpegTSContext),
  2363. .read_probe = mpegts_probe,
  2364. .read_header = mpegts_read_header,
  2365. .read_packet = mpegts_read_packet,
  2366. .read_close = mpegts_read_close,
  2367. .read_timestamp = mpegts_get_dts,
  2368. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2369. .priv_class = &mpegts_class,
  2370. };
  2371. AVInputFormat ff_mpegtsraw_demuxer = {
  2372. .name = "mpegtsraw",
  2373. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2374. .priv_data_size = sizeof(MpegTSContext),
  2375. .read_header = mpegts_read_header,
  2376. .read_packet = mpegts_raw_read_packet,
  2377. .read_close = mpegts_read_close,
  2378. .read_timestamp = mpegts_get_dts,
  2379. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2380. .priv_class = &mpegtsraw_class,
  2381. };