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.

2678 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 new_pes_packet(PESContext *pes, AVPacket *pkt)
  687. {
  688. av_init_packet(pkt);
  689. pkt->buf = pes->buffer;
  690. pkt->data = pes->buffer->data;
  691. pkt->size = pes->data_index;
  692. if (pes->total_size != MAX_PES_PAYLOAD &&
  693. pes->pes_header_size + pes->data_index != pes->total_size +
  694. PES_START_SIZE) {
  695. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  696. pes->flags |= AV_PKT_FLAG_CORRUPT;
  697. }
  698. memset(pkt->data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  699. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  700. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  701. pkt->stream_index = pes->sub_st->index;
  702. else
  703. pkt->stream_index = pes->st->index;
  704. pkt->pts = pes->pts;
  705. pkt->dts = pes->dts;
  706. /* store position of first TS packet of this PES packet */
  707. pkt->pos = pes->ts_packet_pos;
  708. pkt->flags = pes->flags;
  709. /* reset pts values */
  710. pes->pts = AV_NOPTS_VALUE;
  711. pes->dts = AV_NOPTS_VALUE;
  712. pes->buffer = NULL;
  713. pes->data_index = 0;
  714. pes->flags = 0;
  715. }
  716. static uint64_t get_ts64(GetBitContext *gb, int bits)
  717. {
  718. if (get_bits_left(gb) < bits)
  719. return AV_NOPTS_VALUE;
  720. return get_bits64(gb, bits);
  721. }
  722. static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
  723. const uint8_t *buf, int buf_size)
  724. {
  725. GetBitContext gb;
  726. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  727. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  728. int dts_flag = -1, cts_flag = -1;
  729. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  730. init_get_bits(&gb, buf, buf_size * 8);
  731. if (sl->use_au_start)
  732. au_start_flag = get_bits1(&gb);
  733. if (sl->use_au_end)
  734. au_end_flag = get_bits1(&gb);
  735. if (!sl->use_au_start && !sl->use_au_end)
  736. au_start_flag = au_end_flag = 1;
  737. if (sl->ocr_len > 0)
  738. ocr_flag = get_bits1(&gb);
  739. if (sl->use_idle)
  740. idle_flag = get_bits1(&gb);
  741. if (sl->use_padding)
  742. padding_flag = get_bits1(&gb);
  743. if (padding_flag)
  744. padding_bits = get_bits(&gb, 3);
  745. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  746. if (sl->packet_seq_num_len)
  747. skip_bits_long(&gb, sl->packet_seq_num_len);
  748. if (sl->degr_prior_len)
  749. if (get_bits1(&gb))
  750. skip_bits(&gb, sl->degr_prior_len);
  751. if (ocr_flag)
  752. skip_bits_long(&gb, sl->ocr_len);
  753. if (au_start_flag) {
  754. if (sl->use_rand_acc_pt)
  755. get_bits1(&gb);
  756. if (sl->au_seq_num_len > 0)
  757. skip_bits_long(&gb, sl->au_seq_num_len);
  758. if (sl->use_timestamps) {
  759. dts_flag = get_bits1(&gb);
  760. cts_flag = get_bits1(&gb);
  761. }
  762. }
  763. if (sl->inst_bitrate_len)
  764. inst_bitrate_flag = get_bits1(&gb);
  765. if (dts_flag == 1)
  766. dts = get_ts64(&gb, sl->timestamp_len);
  767. if (cts_flag == 1)
  768. cts = get_ts64(&gb, sl->timestamp_len);
  769. if (sl->au_len > 0)
  770. skip_bits_long(&gb, sl->au_len);
  771. if (inst_bitrate_flag)
  772. skip_bits_long(&gb, sl->inst_bitrate_len);
  773. }
  774. if (dts != AV_NOPTS_VALUE)
  775. pes->dts = dts;
  776. if (cts != AV_NOPTS_VALUE)
  777. pes->pts = cts;
  778. if (sl->timestamp_len && sl->timestamp_res)
  779. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  780. return (get_bits_count(&gb) + 7) >> 3;
  781. }
  782. /* return non zero if a packet could be constructed */
  783. static int mpegts_push_data(MpegTSFilter *filter,
  784. const uint8_t *buf, int buf_size, int is_start,
  785. int64_t pos)
  786. {
  787. PESContext *pes = filter->u.pes_filter.opaque;
  788. MpegTSContext *ts = pes->ts;
  789. const uint8_t *p;
  790. int len, code;
  791. if (!ts->pkt)
  792. return 0;
  793. if (is_start) {
  794. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  795. new_pes_packet(pes, ts->pkt);
  796. ts->stop_parse = 1;
  797. }
  798. pes->state = MPEGTS_HEADER;
  799. pes->data_index = 0;
  800. pes->ts_packet_pos = pos;
  801. }
  802. p = buf;
  803. while (buf_size > 0) {
  804. switch (pes->state) {
  805. case MPEGTS_HEADER:
  806. len = PES_START_SIZE - pes->data_index;
  807. if (len > buf_size)
  808. len = buf_size;
  809. memcpy(pes->header + pes->data_index, p, len);
  810. pes->data_index += len;
  811. p += len;
  812. buf_size -= len;
  813. if (pes->data_index == PES_START_SIZE) {
  814. /* we got all the PES or section header. We can now
  815. * decide */
  816. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  817. pes->header[2] == 0x01) {
  818. /* it must be an mpeg2 PES stream */
  819. code = pes->header[3] | 0x100;
  820. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid,
  821. code);
  822. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  823. (!pes->sub_st ||
  824. pes->sub_st->discard == AVDISCARD_ALL)) ||
  825. code == 0x1be) /* padding_stream */
  826. goto skip;
  827. /* stream not present in PMT */
  828. if (!pes->st) {
  829. pes->st = avformat_new_stream(ts->stream, NULL);
  830. if (!pes->st)
  831. return AVERROR(ENOMEM);
  832. pes->st->id = pes->pid;
  833. mpegts_set_stream_info(pes->st, pes, 0, 0);
  834. }
  835. pes->total_size = AV_RB16(pes->header + 4);
  836. /* NOTE: a zero total size means the PES size is
  837. * unbounded */
  838. if (!pes->total_size)
  839. pes->total_size = MAX_PES_PAYLOAD;
  840. /* allocate pes buffer */
  841. pes->buffer = av_buffer_alloc(pes->total_size +
  842. FF_INPUT_BUFFER_PADDING_SIZE);
  843. if (!pes->buffer)
  844. return AVERROR(ENOMEM);
  845. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  846. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  847. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  848. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  849. pes->state = MPEGTS_PESHEADER;
  850. if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
  851. av_dlog(pes->stream,
  852. "pid=%x stream_type=%x probing\n",
  853. pes->pid,
  854. pes->stream_type);
  855. pes->st->request_probe = 1;
  856. }
  857. } else {
  858. pes->state = MPEGTS_PAYLOAD;
  859. pes->data_index = 0;
  860. }
  861. } else {
  862. /* otherwise, it should be a table */
  863. /* skip packet */
  864. skip:
  865. pes->state = MPEGTS_SKIP;
  866. continue;
  867. }
  868. }
  869. break;
  870. /**********************************************/
  871. /* PES packing parsing */
  872. case MPEGTS_PESHEADER:
  873. len = PES_HEADER_SIZE - pes->data_index;
  874. if (len < 0)
  875. return AVERROR_INVALIDDATA;
  876. if (len > buf_size)
  877. len = buf_size;
  878. memcpy(pes->header + pes->data_index, p, len);
  879. pes->data_index += len;
  880. p += len;
  881. buf_size -= len;
  882. if (pes->data_index == PES_HEADER_SIZE) {
  883. pes->pes_header_size = pes->header[8] + 9;
  884. pes->state = MPEGTS_PESHEADER_FILL;
  885. }
  886. break;
  887. case MPEGTS_PESHEADER_FILL:
  888. len = pes->pes_header_size - pes->data_index;
  889. if (len < 0)
  890. return AVERROR_INVALIDDATA;
  891. if (len > buf_size)
  892. len = buf_size;
  893. memcpy(pes->header + pes->data_index, p, len);
  894. pes->data_index += len;
  895. p += len;
  896. buf_size -= len;
  897. if (pes->data_index == pes->pes_header_size) {
  898. const uint8_t *r;
  899. unsigned int flags, pes_ext, skip;
  900. flags = pes->header[7];
  901. r = pes->header + 9;
  902. pes->pts = AV_NOPTS_VALUE;
  903. pes->dts = AV_NOPTS_VALUE;
  904. if ((flags & 0xc0) == 0x80) {
  905. pes->dts = pes->pts = ff_parse_pes_pts(r);
  906. r += 5;
  907. } else if ((flags & 0xc0) == 0xc0) {
  908. pes->pts = ff_parse_pes_pts(r);
  909. r += 5;
  910. pes->dts = ff_parse_pes_pts(r);
  911. r += 5;
  912. }
  913. pes->extended_stream_id = -1;
  914. if (flags & 0x01) { /* PES extension */
  915. pes_ext = *r++;
  916. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  917. skip = (pes_ext >> 4) & 0xb;
  918. skip += skip & 0x9;
  919. r += skip;
  920. if ((pes_ext & 0x41) == 0x01 &&
  921. (r + 2) <= (pes->header + pes->pes_header_size)) {
  922. /* PES extension 2 */
  923. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  924. pes->extended_stream_id = r[1];
  925. }
  926. }
  927. /* we got the full header. We parse it and get the payload */
  928. pes->state = MPEGTS_PAYLOAD;
  929. pes->data_index = 0;
  930. if (pes->stream_type == 0x12 && buf_size > 0) {
  931. int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
  932. buf_size);
  933. pes->pes_header_size += sl_header_bytes;
  934. p += sl_header_bytes;
  935. buf_size -= sl_header_bytes;
  936. }
  937. if (pes->stream_type == 0x15 && buf_size >= 5) {
  938. /* skip metadata access unit header */
  939. pes->pes_header_size += 5;
  940. p += 5;
  941. buf_size -= 5;
  942. }
  943. if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
  944. AVProgram *p = NULL;
  945. while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
  946. if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
  947. MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
  948. if (f) {
  949. AVStream *st = NULL;
  950. if (f->type == MPEGTS_PES) {
  951. PESContext *pcrpes = f->u.pes_filter.opaque;
  952. if (pcrpes)
  953. st = pcrpes->st;
  954. } else if (f->type == MPEGTS_PCR) {
  955. int i;
  956. for (i = 0; i < p->nb_stream_indexes; i++) {
  957. AVStream *pst = pes->stream->streams[p->stream_index[i]];
  958. if (pst->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  959. st = pst;
  960. }
  961. }
  962. if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
  963. // teletext packets do not always have correct timestamps,
  964. // the standard says they should be handled after 40.6 ms at most,
  965. // and the pcr error to this packet should be no more than 100 ms.
  966. // TODO: we should interpolate the PCR, not just use the last one
  967. int64_t pcr = f->last_pcr / 300;
  968. pes->st->pts_wrap_reference = st->pts_wrap_reference;
  969. pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
  970. if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
  971. pes->pts = pes->dts = pcr;
  972. } else if (pes->dts > pcr + 3654 + 9000) {
  973. pes->pts = pes->dts = pcr + 3654 + 9000;
  974. }
  975. break;
  976. }
  977. }
  978. }
  979. }
  980. }
  981. }
  982. break;
  983. case MPEGTS_PAYLOAD:
  984. if (buf_size > 0 && pes->buffer) {
  985. if (pes->data_index > 0 &&
  986. pes->data_index + buf_size > pes->total_size) {
  987. new_pes_packet(pes, ts->pkt);
  988. pes->total_size = MAX_PES_PAYLOAD;
  989. pes->buffer = av_buffer_alloc(pes->total_size +
  990. FF_INPUT_BUFFER_PADDING_SIZE);
  991. if (!pes->buffer)
  992. return AVERROR(ENOMEM);
  993. ts->stop_parse = 1;
  994. } else if (pes->data_index == 0 &&
  995. buf_size > pes->total_size) {
  996. // pes packet size is < ts size packet and pes data is padded with 0xff
  997. // not sure if this is legal in ts but see issue #2392
  998. buf_size = pes->total_size;
  999. }
  1000. memcpy(pes->buffer->data + pes->data_index, p, buf_size);
  1001. pes->data_index += buf_size;
  1002. }
  1003. buf_size = 0;
  1004. /* emit complete packets with known packet size
  1005. * decreases demuxer delay for infrequent packets like subtitles from
  1006. * a couple of seconds to milliseconds for properly muxed files.
  1007. * total_size is the number of bytes following pes_packet_length
  1008. * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
  1009. if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  1010. pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
  1011. ts->stop_parse = 1;
  1012. new_pes_packet(pes, ts->pkt);
  1013. }
  1014. break;
  1015. case MPEGTS_SKIP:
  1016. buf_size = 0;
  1017. break;
  1018. }
  1019. }
  1020. return 0;
  1021. }
  1022. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  1023. {
  1024. MpegTSFilter *tss;
  1025. PESContext *pes;
  1026. /* if no pid found, then add a pid context */
  1027. pes = av_mallocz(sizeof(PESContext));
  1028. if (!pes)
  1029. return 0;
  1030. pes->ts = ts;
  1031. pes->stream = ts->stream;
  1032. pes->pid = pid;
  1033. pes->pcr_pid = pcr_pid;
  1034. pes->state = MPEGTS_SKIP;
  1035. pes->pts = AV_NOPTS_VALUE;
  1036. pes->dts = AV_NOPTS_VALUE;
  1037. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  1038. if (!tss) {
  1039. av_free(pes);
  1040. return 0;
  1041. }
  1042. return pes;
  1043. }
  1044. #define MAX_LEVEL 4
  1045. typedef struct {
  1046. AVFormatContext *s;
  1047. AVIOContext pb;
  1048. Mp4Descr *descr;
  1049. Mp4Descr *active_descr;
  1050. int descr_count;
  1051. int max_descr_count;
  1052. int level;
  1053. } MP4DescrParseContext;
  1054. static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
  1055. const uint8_t *buf, unsigned size,
  1056. Mp4Descr *descr, int max_descr_count)
  1057. {
  1058. int ret;
  1059. if (size > (1 << 30))
  1060. return AVERROR_INVALIDDATA;
  1061. if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
  1062. NULL, NULL, NULL, NULL)) < 0)
  1063. return ret;
  1064. d->s = s;
  1065. d->level = 0;
  1066. d->descr_count = 0;
  1067. d->descr = descr;
  1068. d->active_descr = NULL;
  1069. d->max_descr_count = max_descr_count;
  1070. return 0;
  1071. }
  1072. static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
  1073. {
  1074. int64_t new_off = avio_tell(pb);
  1075. (*len) -= new_off - *off;
  1076. *off = new_off;
  1077. }
  1078. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1079. int target_tag);
  1080. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  1081. {
  1082. while (len > 0) {
  1083. int ret = parse_mp4_descr(d, off, len, 0);
  1084. if (ret < 0)
  1085. return ret;
  1086. update_offsets(&d->pb, &off, &len);
  1087. }
  1088. return 0;
  1089. }
  1090. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1091. {
  1092. avio_rb16(&d->pb); // ID
  1093. avio_r8(&d->pb);
  1094. avio_r8(&d->pb);
  1095. avio_r8(&d->pb);
  1096. avio_r8(&d->pb);
  1097. avio_r8(&d->pb);
  1098. update_offsets(&d->pb, &off, &len);
  1099. return parse_mp4_descr_arr(d, off, len);
  1100. }
  1101. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1102. {
  1103. int id_flags;
  1104. if (len < 2)
  1105. return 0;
  1106. id_flags = avio_rb16(&d->pb);
  1107. if (!(id_flags & 0x0020)) { // URL_Flag
  1108. update_offsets(&d->pb, &off, &len);
  1109. return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
  1110. } else {
  1111. return 0;
  1112. }
  1113. }
  1114. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1115. {
  1116. int es_id = 0;
  1117. if (d->descr_count >= d->max_descr_count)
  1118. return AVERROR_INVALIDDATA;
  1119. ff_mp4_parse_es_descr(&d->pb, &es_id);
  1120. d->active_descr = d->descr + (d->descr_count++);
  1121. d->active_descr->es_id = es_id;
  1122. update_offsets(&d->pb, &off, &len);
  1123. parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  1124. update_offsets(&d->pb, &off, &len);
  1125. if (len > 0)
  1126. parse_mp4_descr(d, off, len, MP4SLDescrTag);
  1127. d->active_descr = NULL;
  1128. return 0;
  1129. }
  1130. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
  1131. int len)
  1132. {
  1133. Mp4Descr *descr = d->active_descr;
  1134. if (!descr)
  1135. return AVERROR_INVALIDDATA;
  1136. d->active_descr->dec_config_descr = av_malloc(len);
  1137. if (!descr->dec_config_descr)
  1138. return AVERROR(ENOMEM);
  1139. descr->dec_config_descr_len = len;
  1140. avio_read(&d->pb, descr->dec_config_descr, len);
  1141. return 0;
  1142. }
  1143. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1144. {
  1145. Mp4Descr *descr = d->active_descr;
  1146. int predefined;
  1147. if (!descr)
  1148. return AVERROR_INVALIDDATA;
  1149. predefined = avio_r8(&d->pb);
  1150. if (!predefined) {
  1151. int lengths;
  1152. int flags = avio_r8(&d->pb);
  1153. descr->sl.use_au_start = !!(flags & 0x80);
  1154. descr->sl.use_au_end = !!(flags & 0x40);
  1155. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  1156. descr->sl.use_padding = !!(flags & 0x08);
  1157. descr->sl.use_timestamps = !!(flags & 0x04);
  1158. descr->sl.use_idle = !!(flags & 0x02);
  1159. descr->sl.timestamp_res = avio_rb32(&d->pb);
  1160. avio_rb32(&d->pb);
  1161. descr->sl.timestamp_len = avio_r8(&d->pb);
  1162. if (descr->sl.timestamp_len > 64) {
  1163. avpriv_request_sample(NULL, "timestamp_len > 64");
  1164. descr->sl.timestamp_len = 64;
  1165. return AVERROR_PATCHWELCOME;
  1166. }
  1167. descr->sl.ocr_len = avio_r8(&d->pb);
  1168. descr->sl.au_len = avio_r8(&d->pb);
  1169. descr->sl.inst_bitrate_len = avio_r8(&d->pb);
  1170. lengths = avio_rb16(&d->pb);
  1171. descr->sl.degr_prior_len = lengths >> 12;
  1172. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  1173. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  1174. } else {
  1175. avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
  1176. }
  1177. return 0;
  1178. }
  1179. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1180. int target_tag)
  1181. {
  1182. int tag;
  1183. int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  1184. update_offsets(&d->pb, &off, &len);
  1185. if (len < 0 || len1 > len || len1 <= 0) {
  1186. av_log(d->s, AV_LOG_ERROR,
  1187. "Tag %x length violation new length %d bytes remaining %d\n",
  1188. tag, len1, len);
  1189. return AVERROR_INVALIDDATA;
  1190. }
  1191. if (d->level++ >= MAX_LEVEL) {
  1192. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  1193. goto done;
  1194. }
  1195. if (target_tag && tag != target_tag) {
  1196. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
  1197. target_tag);
  1198. goto done;
  1199. }
  1200. switch (tag) {
  1201. case MP4IODescrTag:
  1202. parse_MP4IODescrTag(d, off, len1);
  1203. break;
  1204. case MP4ODescrTag:
  1205. parse_MP4ODescrTag(d, off, len1);
  1206. break;
  1207. case MP4ESDescrTag:
  1208. parse_MP4ESDescrTag(d, off, len1);
  1209. break;
  1210. case MP4DecConfigDescrTag:
  1211. parse_MP4DecConfigDescrTag(d, off, len1);
  1212. break;
  1213. case MP4SLDescrTag:
  1214. parse_MP4SLDescrTag(d, off, len1);
  1215. break;
  1216. }
  1217. done:
  1218. d->level--;
  1219. avio_seek(&d->pb, off + len1, SEEK_SET);
  1220. return 0;
  1221. }
  1222. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1223. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1224. {
  1225. MP4DescrParseContext d;
  1226. int ret;
  1227. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1228. if (ret < 0)
  1229. return ret;
  1230. ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1231. *descr_count = d.descr_count;
  1232. return ret;
  1233. }
  1234. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1235. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1236. {
  1237. MP4DescrParseContext d;
  1238. int ret;
  1239. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1240. if (ret < 0)
  1241. return ret;
  1242. ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1243. *descr_count = d.descr_count;
  1244. return ret;
  1245. }
  1246. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
  1247. int section_len)
  1248. {
  1249. MpegTSContext *ts = filter->u.section_filter.opaque;
  1250. SectionHeader h;
  1251. const uint8_t *p, *p_end;
  1252. AVIOContext pb;
  1253. int mp4_descr_count = 0;
  1254. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1255. int i, pid;
  1256. AVFormatContext *s = ts->stream;
  1257. p_end = section + section_len - 4;
  1258. p = section;
  1259. if (parse_section_header(&h, &p, p_end) < 0)
  1260. return;
  1261. if (h.tid != M4OD_TID)
  1262. return;
  1263. mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
  1264. MAX_MP4_DESCR_COUNT);
  1265. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1266. if (!ts->pids[pid])
  1267. continue;
  1268. for (i = 0; i < mp4_descr_count; i++) {
  1269. PESContext *pes;
  1270. AVStream *st;
  1271. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1272. continue;
  1273. if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
  1274. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1275. continue;
  1276. }
  1277. pes = ts->pids[pid]->u.pes_filter.opaque;
  1278. st = pes->st;
  1279. if (!st)
  1280. continue;
  1281. pes->sl = mp4_descr[i].sl;
  1282. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1283. mp4_descr[i].dec_config_descr_len, 0,
  1284. NULL, NULL, NULL, NULL);
  1285. ff_mp4_read_dec_config_descr(s, st, &pb);
  1286. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1287. st->codec->extradata_size > 0)
  1288. st->need_parsing = 0;
  1289. if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1290. st->codec->extradata_size > 0)
  1291. st->need_parsing = 0;
  1292. if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1293. // do nothing
  1294. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO)
  1295. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1296. else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
  1297. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1298. else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
  1299. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1300. }
  1301. }
  1302. for (i = 0; i < mp4_descr_count; i++)
  1303. av_free(mp4_descr[i].dec_config_descr);
  1304. }
  1305. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1306. const uint8_t **pp, const uint8_t *desc_list_end,
  1307. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1308. MpegTSContext *ts)
  1309. {
  1310. const uint8_t *desc_end;
  1311. int desc_len, desc_tag, desc_es_id;
  1312. char language[252];
  1313. int i;
  1314. desc_tag = get8(pp, desc_list_end);
  1315. if (desc_tag < 0)
  1316. return AVERROR_INVALIDDATA;
  1317. desc_len = get8(pp, desc_list_end);
  1318. if (desc_len < 0)
  1319. return AVERROR_INVALIDDATA;
  1320. desc_end = *pp + desc_len;
  1321. if (desc_end > desc_list_end)
  1322. return AVERROR_INVALIDDATA;
  1323. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1324. if (st->codec->codec_id == AV_CODEC_ID_NONE &&
  1325. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1326. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1327. switch (desc_tag) {
  1328. case 0x1E: /* SL descriptor */
  1329. desc_es_id = get16(pp, desc_end);
  1330. if (ts && ts->pids[pid])
  1331. ts->pids[pid]->es_id = desc_es_id;
  1332. for (i = 0; i < mp4_descr_count; i++)
  1333. if (mp4_descr[i].dec_config_descr_len &&
  1334. mp4_descr[i].es_id == desc_es_id) {
  1335. AVIOContext pb;
  1336. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1337. mp4_descr[i].dec_config_descr_len, 0,
  1338. NULL, NULL, NULL, NULL);
  1339. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1340. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1341. st->codec->extradata_size > 0)
  1342. st->need_parsing = 0;
  1343. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1344. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1345. }
  1346. break;
  1347. case 0x1F: /* FMC descriptor */
  1348. get16(pp, desc_end);
  1349. if (mp4_descr_count > 0 &&
  1350. (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe > 0) &&
  1351. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1352. AVIOContext pb;
  1353. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1354. mp4_descr->dec_config_descr_len, 0,
  1355. NULL, NULL, NULL, NULL);
  1356. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1357. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1358. st->codec->extradata_size > 0) {
  1359. st->request_probe = st->need_parsing = 0;
  1360. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1361. }
  1362. }
  1363. break;
  1364. case 0x56: /* DVB teletext descriptor */
  1365. {
  1366. uint8_t *extradata = NULL;
  1367. int language_count = desc_len / 5;
  1368. if (desc_len > 0 && desc_len % 5 != 0)
  1369. return AVERROR_INVALIDDATA;
  1370. if (language_count > 0) {
  1371. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1372. if (language_count > sizeof(language) / 4) {
  1373. language_count = sizeof(language) / 4;
  1374. }
  1375. if (st->codec->extradata == NULL) {
  1376. if (ff_alloc_extradata(st->codec, language_count * 2)) {
  1377. return AVERROR(ENOMEM);
  1378. }
  1379. }
  1380. if (st->codec->extradata_size < language_count * 2)
  1381. return AVERROR_INVALIDDATA;
  1382. extradata = st->codec->extradata;
  1383. for (i = 0; i < language_count; i++) {
  1384. language[i * 4 + 0] = get8(pp, desc_end);
  1385. language[i * 4 + 1] = get8(pp, desc_end);
  1386. language[i * 4 + 2] = get8(pp, desc_end);
  1387. language[i * 4 + 3] = ',';
  1388. memcpy(extradata, *pp, 2);
  1389. extradata += 2;
  1390. *pp += 2;
  1391. }
  1392. language[i * 4 - 1] = 0;
  1393. av_dict_set(&st->metadata, "language", language, 0);
  1394. }
  1395. }
  1396. break;
  1397. case 0x59: /* subtitling descriptor */
  1398. {
  1399. /* 8 bytes per DVB subtitle substream data:
  1400. * ISO_639_language_code (3 bytes),
  1401. * subtitling_type (1 byte),
  1402. * composition_page_id (2 bytes),
  1403. * ancillary_page_id (2 bytes) */
  1404. int language_count = desc_len / 8;
  1405. if (desc_len > 0 && desc_len % 8 != 0)
  1406. return AVERROR_INVALIDDATA;
  1407. if (language_count > 1) {
  1408. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1409. }
  1410. if (language_count > 0) {
  1411. uint8_t *extradata;
  1412. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1413. if (language_count > sizeof(language) / 4) {
  1414. language_count = sizeof(language) / 4;
  1415. }
  1416. if (st->codec->extradata == NULL) {
  1417. if (ff_alloc_extradata(st->codec, language_count * 5)) {
  1418. return AVERROR(ENOMEM);
  1419. }
  1420. }
  1421. if (st->codec->extradata_size < language_count * 5)
  1422. return AVERROR_INVALIDDATA;
  1423. extradata = st->codec->extradata;
  1424. for (i = 0; i < language_count; i++) {
  1425. language[i * 4 + 0] = get8(pp, desc_end);
  1426. language[i * 4 + 1] = get8(pp, desc_end);
  1427. language[i * 4 + 2] = get8(pp, desc_end);
  1428. language[i * 4 + 3] = ',';
  1429. /* hearing impaired subtitles detection using subtitling_type */
  1430. switch (*pp[0]) {
  1431. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1432. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1433. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1434. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1435. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1436. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1437. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1438. break;
  1439. }
  1440. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1441. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1442. extradata += 5;
  1443. *pp += 4;
  1444. }
  1445. language[i * 4 - 1] = 0;
  1446. av_dict_set(&st->metadata, "language", language, 0);
  1447. }
  1448. }
  1449. break;
  1450. case 0x0a: /* ISO 639 language descriptor */
  1451. for (i = 0; i + 4 <= desc_len; i += 4) {
  1452. language[i + 0] = get8(pp, desc_end);
  1453. language[i + 1] = get8(pp, desc_end);
  1454. language[i + 2] = get8(pp, desc_end);
  1455. language[i + 3] = ',';
  1456. switch (get8(pp, desc_end)) {
  1457. case 0x01:
  1458. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1459. break;
  1460. case 0x02:
  1461. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1462. break;
  1463. case 0x03:
  1464. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1465. break;
  1466. }
  1467. }
  1468. if (i) {
  1469. language[i - 1] = 0;
  1470. av_dict_set(&st->metadata, "language", language, 0);
  1471. }
  1472. break;
  1473. case 0x05: /* registration descriptor */
  1474. st->codec->codec_tag = bytestream_get_le32(pp);
  1475. av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
  1476. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1477. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1478. break;
  1479. case 0x52: /* stream identifier descriptor */
  1480. st->stream_identifier = 1 + get8(pp, desc_end);
  1481. break;
  1482. case 0x26: /* metadata descriptor */
  1483. if (get16(pp, desc_end) == 0xFFFF)
  1484. *pp += 4;
  1485. if (get8(pp, desc_end) == 0xFF) {
  1486. st->codec->codec_tag = bytestream_get_le32(pp);
  1487. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1488. mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
  1489. }
  1490. break;
  1491. default:
  1492. break;
  1493. }
  1494. *pp = desc_end;
  1495. return 0;
  1496. }
  1497. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1498. {
  1499. MpegTSContext *ts = filter->u.section_filter.opaque;
  1500. SectionHeader h1, *h = &h1;
  1501. PESContext *pes;
  1502. AVStream *st;
  1503. const uint8_t *p, *p_end, *desc_list_end;
  1504. int program_info_length, pcr_pid, pid, stream_type;
  1505. int desc_list_len;
  1506. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1507. int mp4_descr_count = 0;
  1508. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1509. int i;
  1510. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1511. hex_dump_debug(ts->stream, section, section_len);
  1512. p_end = section + section_len - 4;
  1513. p = section;
  1514. if (parse_section_header(h, &p, p_end) < 0)
  1515. return;
  1516. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1517. h->id, h->sec_num, h->last_sec_num);
  1518. if (h->tid != PMT_TID)
  1519. return;
  1520. clear_program(ts, h->id);
  1521. pcr_pid = get16(&p, p_end);
  1522. if (pcr_pid < 0)
  1523. return;
  1524. pcr_pid &= 0x1fff;
  1525. add_pid_to_pmt(ts, h->id, pcr_pid);
  1526. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1527. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1528. program_info_length = get16(&p, p_end);
  1529. if (program_info_length < 0)
  1530. return;
  1531. program_info_length &= 0xfff;
  1532. while (program_info_length >= 2) {
  1533. uint8_t tag, len;
  1534. tag = get8(&p, p_end);
  1535. len = get8(&p, p_end);
  1536. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1537. if (len > program_info_length - 2)
  1538. // something else is broken, exit the program_descriptors_loop
  1539. break;
  1540. program_info_length -= len + 2;
  1541. if (tag == 0x1d) { // IOD descriptor
  1542. get8(&p, p_end); // scope
  1543. get8(&p, p_end); // label
  1544. len -= 2;
  1545. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1546. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1547. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1548. prog_reg_desc = bytestream_get_le32(&p);
  1549. len -= 4;
  1550. }
  1551. p += len;
  1552. }
  1553. p += program_info_length;
  1554. if (p >= p_end)
  1555. goto out;
  1556. // stop parsing after pmt, we found header
  1557. if (!ts->stream->nb_streams)
  1558. ts->stop_parse = 2;
  1559. set_pmt_found(ts, h->id);
  1560. for (;;) {
  1561. st = 0;
  1562. pes = NULL;
  1563. stream_type = get8(&p, p_end);
  1564. if (stream_type < 0)
  1565. break;
  1566. pid = get16(&p, p_end);
  1567. if (pid < 0)
  1568. goto out;
  1569. pid &= 0x1fff;
  1570. if (pid == ts->current_pid)
  1571. goto out;
  1572. /* now create stream */
  1573. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1574. pes = ts->pids[pid]->u.pes_filter.opaque;
  1575. if (!pes->st) {
  1576. pes->st = avformat_new_stream(pes->stream, NULL);
  1577. if (!pes->st)
  1578. goto out;
  1579. pes->st->id = pes->pid;
  1580. }
  1581. st = pes->st;
  1582. } else if (stream_type != 0x13) {
  1583. if (ts->pids[pid])
  1584. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1585. pes = add_pes_stream(ts, pid, pcr_pid);
  1586. if (pes) {
  1587. st = avformat_new_stream(pes->stream, NULL);
  1588. if (!st)
  1589. goto out;
  1590. st->id = pes->pid;
  1591. }
  1592. } else {
  1593. int idx = ff_find_stream_index(ts->stream, pid);
  1594. if (idx >= 0) {
  1595. st = ts->stream->streams[idx];
  1596. } else {
  1597. st = avformat_new_stream(ts->stream, NULL);
  1598. if (!st)
  1599. goto out;
  1600. st->id = pid;
  1601. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1602. }
  1603. }
  1604. if (!st)
  1605. goto out;
  1606. if (pes && !pes->stream_type)
  1607. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1608. add_pid_to_pmt(ts, h->id, pid);
  1609. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1610. desc_list_len = get16(&p, p_end);
  1611. if (desc_list_len < 0)
  1612. goto out;
  1613. desc_list_len &= 0xfff;
  1614. desc_list_end = p + desc_list_len;
  1615. if (desc_list_end > p_end)
  1616. goto out;
  1617. for (;;) {
  1618. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1619. desc_list_end, mp4_descr,
  1620. mp4_descr_count, pid, ts) < 0)
  1621. break;
  1622. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1623. stream_type == 0x83 && pes->sub_st) {
  1624. ff_program_add_stream_index(ts->stream, h->id,
  1625. pes->sub_st->index);
  1626. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1627. }
  1628. }
  1629. p = desc_list_end;
  1630. }
  1631. if (!ts->pids[pcr_pid])
  1632. mpegts_open_pcr_filter(ts, pcr_pid);
  1633. out:
  1634. for (i = 0; i < mp4_descr_count; i++)
  1635. av_free(mp4_descr[i].dec_config_descr);
  1636. }
  1637. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1638. {
  1639. MpegTSContext *ts = filter->u.section_filter.opaque;
  1640. SectionHeader h1, *h = &h1;
  1641. const uint8_t *p, *p_end;
  1642. int sid, pmt_pid;
  1643. AVProgram *program;
  1644. av_dlog(ts->stream, "PAT:\n");
  1645. hex_dump_debug(ts->stream, section, section_len);
  1646. p_end = section + section_len - 4;
  1647. p = section;
  1648. if (parse_section_header(h, &p, p_end) < 0)
  1649. return;
  1650. if (h->tid != PAT_TID)
  1651. return;
  1652. ts->stream->ts_id = h->id;
  1653. clear_programs(ts);
  1654. for (;;) {
  1655. sid = get16(&p, p_end);
  1656. if (sid < 0)
  1657. break;
  1658. pmt_pid = get16(&p, p_end);
  1659. if (pmt_pid < 0)
  1660. break;
  1661. pmt_pid &= 0x1fff;
  1662. if (pmt_pid == ts->current_pid)
  1663. break;
  1664. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1665. if (sid == 0x0000) {
  1666. /* NIT info */
  1667. } else {
  1668. MpegTSFilter *fil = ts->pids[pmt_pid];
  1669. program = av_new_program(ts->stream, sid);
  1670. program->program_num = sid;
  1671. program->pmt_pid = pmt_pid;
  1672. if (fil)
  1673. if ( fil->type != MPEGTS_SECTION
  1674. || fil->pid != pmt_pid
  1675. || fil->u.section_filter.section_cb != pmt_cb)
  1676. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1677. if (!ts->pids[pmt_pid])
  1678. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1679. add_pat_entry(ts, sid);
  1680. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1681. add_pid_to_pmt(ts, sid, pmt_pid);
  1682. }
  1683. }
  1684. if (sid < 0) {
  1685. int i,j;
  1686. for (j=0; j<ts->stream->nb_programs; j++) {
  1687. for (i = 0; i < ts->nb_prg; i++)
  1688. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1689. break;
  1690. if (i==ts->nb_prg)
  1691. clear_avprogram(ts, ts->stream->programs[j]->id);
  1692. }
  1693. }
  1694. }
  1695. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1696. {
  1697. MpegTSContext *ts = filter->u.section_filter.opaque;
  1698. SectionHeader h1, *h = &h1;
  1699. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1700. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1701. char *name, *provider_name;
  1702. av_dlog(ts->stream, "SDT:\n");
  1703. hex_dump_debug(ts->stream, section, section_len);
  1704. p_end = section + section_len - 4;
  1705. p = section;
  1706. if (parse_section_header(h, &p, p_end) < 0)
  1707. return;
  1708. if (h->tid != SDT_TID)
  1709. return;
  1710. onid = get16(&p, p_end);
  1711. if (onid < 0)
  1712. return;
  1713. val = get8(&p, p_end);
  1714. if (val < 0)
  1715. return;
  1716. for (;;) {
  1717. sid = get16(&p, p_end);
  1718. if (sid < 0)
  1719. break;
  1720. val = get8(&p, p_end);
  1721. if (val < 0)
  1722. break;
  1723. desc_list_len = get16(&p, p_end);
  1724. if (desc_list_len < 0)
  1725. break;
  1726. desc_list_len &= 0xfff;
  1727. desc_list_end = p + desc_list_len;
  1728. if (desc_list_end > p_end)
  1729. break;
  1730. for (;;) {
  1731. desc_tag = get8(&p, desc_list_end);
  1732. if (desc_tag < 0)
  1733. break;
  1734. desc_len = get8(&p, desc_list_end);
  1735. desc_end = p + desc_len;
  1736. if (desc_end > desc_list_end)
  1737. break;
  1738. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1739. desc_tag, desc_len);
  1740. switch (desc_tag) {
  1741. case 0x48:
  1742. service_type = get8(&p, p_end);
  1743. if (service_type < 0)
  1744. break;
  1745. provider_name = getstr8(&p, p_end);
  1746. if (!provider_name)
  1747. break;
  1748. name = getstr8(&p, p_end);
  1749. if (name) {
  1750. AVProgram *program = av_new_program(ts->stream, sid);
  1751. if (program) {
  1752. av_dict_set(&program->metadata, "service_name", name, 0);
  1753. av_dict_set(&program->metadata, "service_provider",
  1754. provider_name, 0);
  1755. }
  1756. }
  1757. av_free(name);
  1758. av_free(provider_name);
  1759. break;
  1760. default:
  1761. break;
  1762. }
  1763. p = desc_end;
  1764. }
  1765. p = desc_list_end;
  1766. }
  1767. }
  1768. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1769. const uint8_t *packet);
  1770. /* handle one TS packet */
  1771. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1772. {
  1773. AVFormatContext *s = ts->stream;
  1774. MpegTSFilter *tss;
  1775. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1776. has_adaptation, has_payload;
  1777. const uint8_t *p, *p_end;
  1778. int64_t pos;
  1779. pid = AV_RB16(packet + 1) & 0x1fff;
  1780. if (pid && discard_pid(ts, pid))
  1781. return 0;
  1782. is_start = packet[1] & 0x40;
  1783. tss = ts->pids[pid];
  1784. if (ts->auto_guess && tss == NULL && is_start) {
  1785. add_pes_stream(ts, pid, -1);
  1786. tss = ts->pids[pid];
  1787. }
  1788. if (!tss)
  1789. return 0;
  1790. ts->current_pid = pid;
  1791. afc = (packet[3] >> 4) & 3;
  1792. if (afc == 0) /* reserved value */
  1793. return 0;
  1794. has_adaptation = afc & 2;
  1795. has_payload = afc & 1;
  1796. is_discontinuity = has_adaptation &&
  1797. packet[4] != 0 && /* with length > 0 */
  1798. (packet[5] & 0x80); /* and discontinuity indicated */
  1799. /* continuity check (currently not used) */
  1800. cc = (packet[3] & 0xf);
  1801. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1802. cc_ok = pid == 0x1FFF || // null packet PID
  1803. is_discontinuity ||
  1804. tss->last_cc < 0 ||
  1805. expected_cc == cc;
  1806. tss->last_cc = cc;
  1807. if (!cc_ok) {
  1808. av_log(ts->stream, AV_LOG_DEBUG,
  1809. "Continuity check failed for pid %d expected %d got %d\n",
  1810. pid, expected_cc, cc);
  1811. if (tss->type == MPEGTS_PES) {
  1812. PESContext *pc = tss->u.pes_filter.opaque;
  1813. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1814. }
  1815. }
  1816. if (!has_payload && tss->type != MPEGTS_PCR)
  1817. return 0;
  1818. p = packet + 4;
  1819. if (has_adaptation) {
  1820. /* skip adaptation field */
  1821. p += p[0] + 1;
  1822. }
  1823. /* if past the end of packet, ignore */
  1824. p_end = packet + TS_PACKET_SIZE;
  1825. if (p > p_end || (p == p_end && tss->type != MPEGTS_PCR))
  1826. return 0;
  1827. pos = avio_tell(ts->stream->pb);
  1828. if (pos >= 0) {
  1829. av_assert0(pos >= TS_PACKET_SIZE);
  1830. ts->pos47_full = pos - TS_PACKET_SIZE;
  1831. }
  1832. if (tss->type == MPEGTS_SECTION) {
  1833. if (is_start) {
  1834. /* pointer field present */
  1835. len = *p++;
  1836. if (p + len > p_end)
  1837. return 0;
  1838. if (len && cc_ok) {
  1839. /* write remaining section bytes */
  1840. write_section_data(s, tss,
  1841. p, len, 0);
  1842. /* check whether filter has been closed */
  1843. if (!ts->pids[pid])
  1844. return 0;
  1845. }
  1846. p += len;
  1847. if (p < p_end) {
  1848. write_section_data(s, tss,
  1849. p, p_end - p, 1);
  1850. }
  1851. } else {
  1852. if (cc_ok) {
  1853. write_section_data(s, tss,
  1854. p, p_end - p, 0);
  1855. }
  1856. }
  1857. // stop find_stream_info from waiting for more streams
  1858. // when all programs have received a PMT
  1859. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER) {
  1860. int i;
  1861. for (i = 0; i < ts->nb_prg; i++) {
  1862. if (!ts->prg[i].pmt_found)
  1863. break;
  1864. }
  1865. if (i == ts->nb_prg && ts->nb_prg > 0) {
  1866. if (ts->stream->nb_streams > 1 || pos > 100000) {
  1867. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  1868. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1869. }
  1870. }
  1871. }
  1872. } else {
  1873. int ret;
  1874. int64_t pcr_h;
  1875. int pcr_l;
  1876. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1877. tss->last_pcr = pcr_h * 300 + pcr_l;
  1878. // Note: The position here points actually behind the current packet.
  1879. if (tss->type == MPEGTS_PES) {
  1880. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1881. pos - ts->raw_packet_size)) < 0)
  1882. return ret;
  1883. }
  1884. }
  1885. return 0;
  1886. }
  1887. static void reanalyze(MpegTSContext *ts) {
  1888. AVIOContext *pb = ts->stream->pb;
  1889. int64_t pos = avio_tell(pb);
  1890. if (pos < 0)
  1891. return;
  1892. pos -= ts->pos47_full;
  1893. if (pos == TS_PACKET_SIZE) {
  1894. ts->size_stat[0] ++;
  1895. } else if (pos == TS_DVHS_PACKET_SIZE) {
  1896. ts->size_stat[1] ++;
  1897. } else if (pos == TS_FEC_PACKET_SIZE) {
  1898. ts->size_stat[2] ++;
  1899. }
  1900. ts->size_stat_count ++;
  1901. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  1902. int newsize = 0;
  1903. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  1904. newsize = TS_PACKET_SIZE;
  1905. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  1906. newsize = TS_DVHS_PACKET_SIZE;
  1907. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  1908. newsize = TS_FEC_PACKET_SIZE;
  1909. }
  1910. if (newsize && newsize != ts->raw_packet_size) {
  1911. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  1912. ts->raw_packet_size = newsize;
  1913. }
  1914. ts->size_stat_count = 0;
  1915. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  1916. }
  1917. }
  1918. /* XXX: try to find a better synchro over several packets (use
  1919. * get_packet_size() ?) */
  1920. static int mpegts_resync(AVFormatContext *s)
  1921. {
  1922. AVIOContext *pb = s->pb;
  1923. int c, i;
  1924. for (i = 0; i < MAX_RESYNC_SIZE; i++) {
  1925. c = avio_r8(pb);
  1926. if (url_feof(pb))
  1927. return AVERROR_EOF;
  1928. if (c == 0x47) {
  1929. avio_seek(pb, -1, SEEK_CUR);
  1930. reanalyze(s->priv_data);
  1931. return 0;
  1932. }
  1933. }
  1934. av_log(s, AV_LOG_ERROR,
  1935. "max resync size reached, could not find sync byte\n");
  1936. /* no sync found */
  1937. return AVERROR_INVALIDDATA;
  1938. }
  1939. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  1940. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  1941. const uint8_t **data)
  1942. {
  1943. AVIOContext *pb = s->pb;
  1944. int len;
  1945. for (;;) {
  1946. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  1947. if (len != TS_PACKET_SIZE)
  1948. return len < 0 ? len : AVERROR_EOF;
  1949. /* check packet sync byte */
  1950. if ((*data)[0] != 0x47) {
  1951. /* find a new packet start */
  1952. uint64_t pos = avio_tell(pb);
  1953. avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
  1954. if (mpegts_resync(s) < 0)
  1955. return AVERROR(EAGAIN);
  1956. else
  1957. continue;
  1958. } else {
  1959. break;
  1960. }
  1961. }
  1962. return 0;
  1963. }
  1964. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  1965. {
  1966. AVIOContext *pb = s->pb;
  1967. int skip = raw_packet_size - TS_PACKET_SIZE;
  1968. if (skip > 0)
  1969. avio_skip(pb, skip);
  1970. }
  1971. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1972. {
  1973. AVFormatContext *s = ts->stream;
  1974. uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  1975. const uint8_t *data;
  1976. int packet_num, ret = 0;
  1977. if (avio_tell(s->pb) != ts->last_pos) {
  1978. int i;
  1979. av_dlog(ts->stream, "Skipping after seek\n");
  1980. /* seek detected, flush pes buffer */
  1981. for (i = 0; i < NB_PID_MAX; i++) {
  1982. if (ts->pids[i]) {
  1983. if (ts->pids[i]->type == MPEGTS_PES) {
  1984. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1985. av_buffer_unref(&pes->buffer);
  1986. pes->data_index = 0;
  1987. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1988. }
  1989. ts->pids[i]->last_cc = -1;
  1990. ts->pids[i]->last_pcr = -1;
  1991. }
  1992. }
  1993. }
  1994. ts->stop_parse = 0;
  1995. packet_num = 0;
  1996. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  1997. for (;;) {
  1998. packet_num++;
  1999. if (nb_packets != 0 && packet_num >= nb_packets ||
  2000. ts->stop_parse > 1) {
  2001. ret = AVERROR(EAGAIN);
  2002. break;
  2003. }
  2004. if (ts->stop_parse > 0)
  2005. break;
  2006. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2007. if (ret != 0)
  2008. break;
  2009. ret = handle_packet(ts, data);
  2010. finished_reading_packet(s, ts->raw_packet_size);
  2011. if (ret != 0)
  2012. break;
  2013. }
  2014. ts->last_pos = avio_tell(s->pb);
  2015. return ret;
  2016. }
  2017. static int mpegts_probe(AVProbeData *p)
  2018. {
  2019. const int size = p->buf_size;
  2020. int maxscore = 0;
  2021. int sumscore = 0;
  2022. int i;
  2023. int check_count = size / TS_FEC_PACKET_SIZE;
  2024. #define CHECK_COUNT 10
  2025. #define CHECK_BLOCK 100
  2026. if (check_count < CHECK_COUNT)
  2027. return AVERROR_INVALIDDATA;
  2028. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2029. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2030. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
  2031. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  2032. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  2033. score = FFMAX3(score, dvhs_score, fec_score);
  2034. sumscore += score;
  2035. maxscore = FFMAX(maxscore, score);
  2036. }
  2037. sumscore = sumscore * CHECK_COUNT / check_count;
  2038. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2039. av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2040. if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2041. else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2042. else
  2043. return AVERROR_INVALIDDATA;
  2044. }
  2045. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2046. * (-1) if not available */
  2047. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2048. {
  2049. int afc, len, flags;
  2050. const uint8_t *p;
  2051. unsigned int v;
  2052. afc = (packet[3] >> 4) & 3;
  2053. if (afc <= 1)
  2054. return AVERROR_INVALIDDATA;
  2055. p = packet + 4;
  2056. len = p[0];
  2057. p++;
  2058. if (len == 0)
  2059. return AVERROR_INVALIDDATA;
  2060. flags = *p++;
  2061. len--;
  2062. if (!(flags & 0x10))
  2063. return AVERROR_INVALIDDATA;
  2064. if (len < 6)
  2065. return AVERROR_INVALIDDATA;
  2066. v = AV_RB32(p);
  2067. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2068. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2069. return 0;
  2070. }
  2071. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2072. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2073. * probe buffer usually is big enough. Only warn if the seek failed
  2074. * on files where the seek should work. */
  2075. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2076. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2077. }
  2078. static int mpegts_read_header(AVFormatContext *s)
  2079. {
  2080. MpegTSContext *ts = s->priv_data;
  2081. AVIOContext *pb = s->pb;
  2082. uint8_t buf[8 * 1024] = {0};
  2083. int len;
  2084. int64_t pos;
  2085. ffio_ensure_seekback(pb, s->probesize);
  2086. /* read the first 8192 bytes to get packet size */
  2087. pos = avio_tell(pb);
  2088. len = avio_read(pb, buf, sizeof(buf));
  2089. ts->raw_packet_size = get_packet_size(buf, len);
  2090. if (ts->raw_packet_size <= 0) {
  2091. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2092. ts->raw_packet_size = TS_PACKET_SIZE;
  2093. }
  2094. ts->stream = s;
  2095. ts->auto_guess = 0;
  2096. if (s->iformat == &ff_mpegts_demuxer) {
  2097. /* normal demux */
  2098. /* first do a scan to get all the services */
  2099. seek_back(s, pb, pos);
  2100. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2101. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2102. handle_packets(ts, s->probesize / ts->raw_packet_size);
  2103. /* if could not find service, enable auto_guess */
  2104. ts->auto_guess = 1;
  2105. av_dlog(ts->stream, "tuning done\n");
  2106. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2107. } else {
  2108. AVStream *st;
  2109. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2110. int64_t pcrs[2], pcr_h;
  2111. int packet_count[2];
  2112. uint8_t packet[TS_PACKET_SIZE];
  2113. const uint8_t *data;
  2114. /* only read packets */
  2115. st = avformat_new_stream(s, NULL);
  2116. if (!st)
  2117. return AVERROR(ENOMEM);
  2118. avpriv_set_pts_info(st, 60, 1, 27000000);
  2119. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2120. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  2121. /* we iterate until we find two PCRs to estimate the bitrate */
  2122. pcr_pid = -1;
  2123. nb_pcrs = 0;
  2124. nb_packets = 0;
  2125. for (;;) {
  2126. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2127. if (ret < 0)
  2128. return ret;
  2129. pid = AV_RB16(data + 1) & 0x1fff;
  2130. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2131. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2132. finished_reading_packet(s, ts->raw_packet_size);
  2133. pcr_pid = pid;
  2134. packet_count[nb_pcrs] = nb_packets;
  2135. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2136. nb_pcrs++;
  2137. if (nb_pcrs >= 2)
  2138. break;
  2139. } else {
  2140. finished_reading_packet(s, ts->raw_packet_size);
  2141. }
  2142. nb_packets++;
  2143. }
  2144. /* NOTE1: the bitrate is computed without the FEC */
  2145. /* NOTE2: it is only the bitrate of the start of the stream */
  2146. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2147. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2148. s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
  2149. st->codec->bit_rate = s->bit_rate;
  2150. st->start_time = ts->cur_pcr;
  2151. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  2152. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2153. }
  2154. seek_back(s, pb, pos);
  2155. return 0;
  2156. }
  2157. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2158. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2159. {
  2160. MpegTSContext *ts = s->priv_data;
  2161. int ret, i;
  2162. int64_t pcr_h, next_pcr_h, pos;
  2163. int pcr_l, next_pcr_l;
  2164. uint8_t pcr_buf[12];
  2165. const uint8_t *data;
  2166. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2167. return AVERROR(ENOMEM);
  2168. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2169. pkt->pos = avio_tell(s->pb);
  2170. if (ret < 0) {
  2171. av_free_packet(pkt);
  2172. return ret;
  2173. }
  2174. if (data != pkt->data)
  2175. memcpy(pkt->data, data, ts->raw_packet_size);
  2176. finished_reading_packet(s, ts->raw_packet_size);
  2177. if (ts->mpeg2ts_compute_pcr) {
  2178. /* compute exact PCR for each packet */
  2179. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2180. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2181. pos = avio_tell(s->pb);
  2182. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2183. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2184. avio_read(s->pb, pcr_buf, 12);
  2185. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2186. /* XXX: not precise enough */
  2187. ts->pcr_incr =
  2188. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2189. (i + 1);
  2190. break;
  2191. }
  2192. }
  2193. avio_seek(s->pb, pos, SEEK_SET);
  2194. /* no next PCR found: we use previous increment */
  2195. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2196. }
  2197. pkt->pts = ts->cur_pcr;
  2198. pkt->duration = ts->pcr_incr;
  2199. ts->cur_pcr += ts->pcr_incr;
  2200. }
  2201. pkt->stream_index = 0;
  2202. return 0;
  2203. }
  2204. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2205. {
  2206. MpegTSContext *ts = s->priv_data;
  2207. int ret, i;
  2208. pkt->size = -1;
  2209. ts->pkt = pkt;
  2210. ret = handle_packets(ts, 0);
  2211. if (ret < 0) {
  2212. av_free_packet(ts->pkt);
  2213. /* flush pes data left */
  2214. for (i = 0; i < NB_PID_MAX; i++)
  2215. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2216. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2217. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2218. new_pes_packet(pes, pkt);
  2219. pes->state = MPEGTS_SKIP;
  2220. ret = 0;
  2221. break;
  2222. }
  2223. }
  2224. }
  2225. if (!ret && pkt->size < 0)
  2226. ret = AVERROR(EINTR);
  2227. return ret;
  2228. }
  2229. static void mpegts_free(MpegTSContext *ts)
  2230. {
  2231. int i;
  2232. clear_programs(ts);
  2233. for (i = 0; i < NB_PID_MAX; i++)
  2234. if (ts->pids[i])
  2235. mpegts_close_filter(ts, ts->pids[i]);
  2236. }
  2237. static int mpegts_read_close(AVFormatContext *s)
  2238. {
  2239. MpegTSContext *ts = s->priv_data;
  2240. mpegts_free(ts);
  2241. return 0;
  2242. }
  2243. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2244. int64_t *ppos, int64_t pos_limit)
  2245. {
  2246. MpegTSContext *ts = s->priv_data;
  2247. int64_t pos, timestamp;
  2248. uint8_t buf[TS_PACKET_SIZE];
  2249. int pcr_l, pcr_pid =
  2250. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2251. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2252. pos =
  2253. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2254. ts->raw_packet_size + pos47;
  2255. while(pos < pos_limit) {
  2256. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2257. return AV_NOPTS_VALUE;
  2258. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2259. return AV_NOPTS_VALUE;
  2260. if (buf[0] != 0x47) {
  2261. avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
  2262. if (mpegts_resync(s) < 0)
  2263. return AV_NOPTS_VALUE;
  2264. pos = avio_tell(s->pb);
  2265. continue;
  2266. }
  2267. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2268. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2269. *ppos = pos;
  2270. return timestamp;
  2271. }
  2272. pos += ts->raw_packet_size;
  2273. }
  2274. return AV_NOPTS_VALUE;
  2275. }
  2276. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2277. int64_t *ppos, int64_t pos_limit)
  2278. {
  2279. MpegTSContext *ts = s->priv_data;
  2280. int64_t pos;
  2281. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2282. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2283. ff_read_frame_flush(s);
  2284. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2285. return AV_NOPTS_VALUE;
  2286. while(pos < pos_limit) {
  2287. int ret;
  2288. AVPacket pkt;
  2289. av_init_packet(&pkt);
  2290. ret = av_read_frame(s, &pkt);
  2291. if (ret < 0)
  2292. return AV_NOPTS_VALUE;
  2293. av_free_packet(&pkt);
  2294. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2295. ff_reduce_index(s, pkt.stream_index);
  2296. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2297. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2298. *ppos = pkt.pos;
  2299. return pkt.dts;
  2300. }
  2301. }
  2302. pos = pkt.pos;
  2303. }
  2304. return AV_NOPTS_VALUE;
  2305. }
  2306. /**************************************************************/
  2307. /* parsing functions - called from other demuxers such as RTP */
  2308. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  2309. {
  2310. MpegTSContext *ts;
  2311. ts = av_mallocz(sizeof(MpegTSContext));
  2312. if (!ts)
  2313. return NULL;
  2314. /* no stream case, currently used by RTP */
  2315. ts->raw_packet_size = TS_PACKET_SIZE;
  2316. ts->stream = s;
  2317. ts->auto_guess = 1;
  2318. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2319. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2320. return ts;
  2321. }
  2322. /* return the consumed length if a packet was output, or -1 if no
  2323. * packet is output */
  2324. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2325. const uint8_t *buf, int len)
  2326. {
  2327. int len1;
  2328. len1 = len;
  2329. ts->pkt = pkt;
  2330. for (;;) {
  2331. ts->stop_parse = 0;
  2332. if (len < TS_PACKET_SIZE)
  2333. return AVERROR_INVALIDDATA;
  2334. if (buf[0] != 0x47) {
  2335. buf++;
  2336. len--;
  2337. } else {
  2338. handle_packet(ts, buf);
  2339. buf += TS_PACKET_SIZE;
  2340. len -= TS_PACKET_SIZE;
  2341. if (ts->stop_parse == 1)
  2342. break;
  2343. }
  2344. }
  2345. return len1 - len;
  2346. }
  2347. void ff_mpegts_parse_close(MpegTSContext *ts)
  2348. {
  2349. mpegts_free(ts);
  2350. av_free(ts);
  2351. }
  2352. AVInputFormat ff_mpegts_demuxer = {
  2353. .name = "mpegts",
  2354. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2355. .priv_data_size = sizeof(MpegTSContext),
  2356. .read_probe = mpegts_probe,
  2357. .read_header = mpegts_read_header,
  2358. .read_packet = mpegts_read_packet,
  2359. .read_close = mpegts_read_close,
  2360. .read_timestamp = mpegts_get_dts,
  2361. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2362. .priv_class = &mpegts_class,
  2363. };
  2364. AVInputFormat ff_mpegtsraw_demuxer = {
  2365. .name = "mpegtsraw",
  2366. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2367. .priv_data_size = sizeof(MpegTSContext),
  2368. .read_header = mpegts_read_header,
  2369. .read_packet = mpegts_raw_read_packet,
  2370. .read_close = mpegts_read_close,
  2371. .read_timestamp = mpegts_get_dts,
  2372. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2373. .priv_class = &mpegtsraw_class,
  2374. };