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.

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