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.

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