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.

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