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.

2703 lines
88KB

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