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.

2702 lines
88KB

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