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.

2378 lines
76KB

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