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.

2654 lines
86KB

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