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.

2738 lines
89KB

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