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.

2652 lines
85KB

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