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.

2322 lines
73KB

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