You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2684 lines
87KB

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