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