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.

2666 lines
86KB

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