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.

2710 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. init_get_bits(&gb, buf, buf_size * 8);
  747. if (sl->use_au_start)
  748. au_start_flag = get_bits1(&gb);
  749. if (sl->use_au_end)
  750. au_end_flag = get_bits1(&gb);
  751. if (!sl->use_au_start && !sl->use_au_end)
  752. au_start_flag = au_end_flag = 1;
  753. if (sl->ocr_len > 0)
  754. ocr_flag = get_bits1(&gb);
  755. if (sl->use_idle)
  756. idle_flag = get_bits1(&gb);
  757. if (sl->use_padding)
  758. padding_flag = get_bits1(&gb);
  759. if (padding_flag)
  760. padding_bits = get_bits(&gb, 3);
  761. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  762. if (sl->packet_seq_num_len)
  763. skip_bits_long(&gb, sl->packet_seq_num_len);
  764. if (sl->degr_prior_len)
  765. if (get_bits1(&gb))
  766. skip_bits(&gb, sl->degr_prior_len);
  767. if (ocr_flag)
  768. skip_bits_long(&gb, sl->ocr_len);
  769. if (au_start_flag) {
  770. if (sl->use_rand_acc_pt)
  771. get_bits1(&gb);
  772. if (sl->au_seq_num_len > 0)
  773. skip_bits_long(&gb, sl->au_seq_num_len);
  774. if (sl->use_timestamps) {
  775. dts_flag = get_bits1(&gb);
  776. cts_flag = get_bits1(&gb);
  777. }
  778. }
  779. if (sl->inst_bitrate_len)
  780. inst_bitrate_flag = get_bits1(&gb);
  781. if (dts_flag == 1)
  782. dts = get_ts64(&gb, sl->timestamp_len);
  783. if (cts_flag == 1)
  784. cts = get_ts64(&gb, sl->timestamp_len);
  785. if (sl->au_len > 0)
  786. skip_bits_long(&gb, sl->au_len);
  787. if (inst_bitrate_flag)
  788. skip_bits_long(&gb, sl->inst_bitrate_len);
  789. }
  790. if (dts != AV_NOPTS_VALUE)
  791. pes->dts = dts;
  792. if (cts != AV_NOPTS_VALUE)
  793. pes->pts = cts;
  794. if (sl->timestamp_len && sl->timestamp_res)
  795. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  796. return (get_bits_count(&gb) + 7) >> 3;
  797. }
  798. /* return non zero if a packet could be constructed */
  799. static int mpegts_push_data(MpegTSFilter *filter,
  800. const uint8_t *buf, int buf_size, int is_start,
  801. int64_t pos)
  802. {
  803. PESContext *pes = filter->u.pes_filter.opaque;
  804. MpegTSContext *ts = pes->ts;
  805. const uint8_t *p;
  806. int len, code;
  807. if (!ts->pkt)
  808. return 0;
  809. if (is_start) {
  810. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  811. new_pes_packet(pes, ts->pkt);
  812. ts->stop_parse = 1;
  813. } else {
  814. reset_pes_packet_state(pes);
  815. }
  816. pes->state = MPEGTS_HEADER;
  817. pes->ts_packet_pos = pos;
  818. }
  819. p = buf;
  820. while (buf_size > 0) {
  821. switch (pes->state) {
  822. case MPEGTS_HEADER:
  823. len = PES_START_SIZE - pes->data_index;
  824. if (len > buf_size)
  825. len = buf_size;
  826. memcpy(pes->header + pes->data_index, p, len);
  827. pes->data_index += len;
  828. p += len;
  829. buf_size -= len;
  830. if (pes->data_index == PES_START_SIZE) {
  831. /* we got all the PES or section header. We can now
  832. * decide */
  833. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  834. pes->header[2] == 0x01) {
  835. /* it must be an mpeg2 PES stream */
  836. code = pes->header[3] | 0x100;
  837. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid,
  838. code);
  839. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  840. (!pes->sub_st ||
  841. pes->sub_st->discard == AVDISCARD_ALL)) ||
  842. code == 0x1be) /* padding_stream */
  843. goto skip;
  844. /* stream not present in PMT */
  845. if (!pes->st) {
  846. if (ts->skip_changes)
  847. goto skip;
  848. pes->st = avformat_new_stream(ts->stream, NULL);
  849. if (!pes->st)
  850. return AVERROR(ENOMEM);
  851. pes->st->id = pes->pid;
  852. mpegts_set_stream_info(pes->st, pes, 0, 0);
  853. }
  854. pes->total_size = AV_RB16(pes->header + 4);
  855. /* NOTE: a zero total size means the PES size is
  856. * unbounded */
  857. if (!pes->total_size)
  858. pes->total_size = MAX_PES_PAYLOAD;
  859. /* allocate pes buffer */
  860. pes->buffer = av_buffer_alloc(pes->total_size +
  861. FF_INPUT_BUFFER_PADDING_SIZE);
  862. if (!pes->buffer)
  863. return AVERROR(ENOMEM);
  864. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  865. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  866. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  867. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  868. pes->state = MPEGTS_PESHEADER;
  869. if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
  870. av_dlog(pes->stream,
  871. "pid=%x stream_type=%x probing\n",
  872. pes->pid,
  873. pes->stream_type);
  874. pes->st->request_probe = 1;
  875. }
  876. } else {
  877. pes->state = MPEGTS_PAYLOAD;
  878. pes->data_index = 0;
  879. }
  880. } else {
  881. /* otherwise, it should be a table */
  882. /* skip packet */
  883. skip:
  884. pes->state = MPEGTS_SKIP;
  885. continue;
  886. }
  887. }
  888. break;
  889. /**********************************************/
  890. /* PES packing parsing */
  891. case MPEGTS_PESHEADER:
  892. len = PES_HEADER_SIZE - pes->data_index;
  893. if (len < 0)
  894. return AVERROR_INVALIDDATA;
  895. if (len > buf_size)
  896. len = buf_size;
  897. memcpy(pes->header + pes->data_index, p, len);
  898. pes->data_index += len;
  899. p += len;
  900. buf_size -= len;
  901. if (pes->data_index == PES_HEADER_SIZE) {
  902. pes->pes_header_size = pes->header[8] + 9;
  903. pes->state = MPEGTS_PESHEADER_FILL;
  904. }
  905. break;
  906. case MPEGTS_PESHEADER_FILL:
  907. len = pes->pes_header_size - pes->data_index;
  908. if (len < 0)
  909. return AVERROR_INVALIDDATA;
  910. if (len > buf_size)
  911. len = buf_size;
  912. memcpy(pes->header + pes->data_index, p, len);
  913. pes->data_index += len;
  914. p += len;
  915. buf_size -= len;
  916. if (pes->data_index == pes->pes_header_size) {
  917. const uint8_t *r;
  918. unsigned int flags, pes_ext, skip;
  919. flags = pes->header[7];
  920. r = pes->header + 9;
  921. pes->pts = AV_NOPTS_VALUE;
  922. pes->dts = AV_NOPTS_VALUE;
  923. if ((flags & 0xc0) == 0x80) {
  924. pes->dts = pes->pts = ff_parse_pes_pts(r);
  925. r += 5;
  926. } else if ((flags & 0xc0) == 0xc0) {
  927. pes->pts = ff_parse_pes_pts(r);
  928. r += 5;
  929. pes->dts = ff_parse_pes_pts(r);
  930. r += 5;
  931. }
  932. pes->extended_stream_id = -1;
  933. if (flags & 0x01) { /* PES extension */
  934. pes_ext = *r++;
  935. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  936. skip = (pes_ext >> 4) & 0xb;
  937. skip += skip & 0x9;
  938. r += skip;
  939. if ((pes_ext & 0x41) == 0x01 &&
  940. (r + 2) <= (pes->header + pes->pes_header_size)) {
  941. /* PES extension 2 */
  942. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  943. pes->extended_stream_id = r[1];
  944. }
  945. }
  946. /* we got the full header. We parse it and get the payload */
  947. pes->state = MPEGTS_PAYLOAD;
  948. pes->data_index = 0;
  949. if (pes->stream_type == 0x12 && buf_size > 0) {
  950. int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
  951. buf_size);
  952. pes->pes_header_size += sl_header_bytes;
  953. p += sl_header_bytes;
  954. buf_size -= sl_header_bytes;
  955. }
  956. if (pes->stream_type == 0x15 && buf_size >= 5) {
  957. /* skip metadata access unit header */
  958. pes->pes_header_size += 5;
  959. p += 5;
  960. buf_size -= 5;
  961. }
  962. if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
  963. AVProgram *p = NULL;
  964. while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
  965. if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
  966. MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
  967. if (f) {
  968. AVStream *st = NULL;
  969. if (f->type == MPEGTS_PES) {
  970. PESContext *pcrpes = f->u.pes_filter.opaque;
  971. if (pcrpes)
  972. st = pcrpes->st;
  973. } else if (f->type == MPEGTS_PCR) {
  974. int i;
  975. for (i = 0; i < p->nb_stream_indexes; i++) {
  976. AVStream *pst = pes->stream->streams[p->stream_index[i]];
  977. if (pst->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  978. st = pst;
  979. }
  980. }
  981. if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
  982. // teletext packets do not always have correct timestamps,
  983. // the standard says they should be handled after 40.6 ms at most,
  984. // and the pcr error to this packet should be no more than 100 ms.
  985. // TODO: we should interpolate the PCR, not just use the last one
  986. int64_t pcr = f->last_pcr / 300;
  987. pes->st->pts_wrap_reference = st->pts_wrap_reference;
  988. pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
  989. if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
  990. pes->pts = pes->dts = pcr;
  991. } else if (pes->dts > pcr + 3654 + 9000) {
  992. pes->pts = pes->dts = pcr + 3654 + 9000;
  993. }
  994. break;
  995. }
  996. }
  997. }
  998. }
  999. }
  1000. }
  1001. break;
  1002. case MPEGTS_PAYLOAD:
  1003. if (pes->buffer) {
  1004. if (pes->data_index > 0 &&
  1005. pes->data_index + buf_size > pes->total_size) {
  1006. new_pes_packet(pes, ts->pkt);
  1007. pes->total_size = MAX_PES_PAYLOAD;
  1008. pes->buffer = av_buffer_alloc(pes->total_size +
  1009. FF_INPUT_BUFFER_PADDING_SIZE);
  1010. if (!pes->buffer)
  1011. return AVERROR(ENOMEM);
  1012. ts->stop_parse = 1;
  1013. } else if (pes->data_index == 0 &&
  1014. buf_size > pes->total_size) {
  1015. // pes packet size is < ts size packet and pes data is padded with 0xff
  1016. // not sure if this is legal in ts but see issue #2392
  1017. buf_size = pes->total_size;
  1018. }
  1019. memcpy(pes->buffer->data + pes->data_index, p, buf_size);
  1020. pes->data_index += buf_size;
  1021. /* emit complete packets with known packet size
  1022. * decreases demuxer delay for infrequent packets like subtitles from
  1023. * a couple of seconds to milliseconds for properly muxed files.
  1024. * total_size is the number of bytes following pes_packet_length
  1025. * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
  1026. if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  1027. pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
  1028. ts->stop_parse = 1;
  1029. new_pes_packet(pes, ts->pkt);
  1030. }
  1031. }
  1032. buf_size = 0;
  1033. break;
  1034. case MPEGTS_SKIP:
  1035. buf_size = 0;
  1036. break;
  1037. }
  1038. }
  1039. return 0;
  1040. }
  1041. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  1042. {
  1043. MpegTSFilter *tss;
  1044. PESContext *pes;
  1045. /* if no pid found, then add a pid context */
  1046. pes = av_mallocz(sizeof(PESContext));
  1047. if (!pes)
  1048. return 0;
  1049. pes->ts = ts;
  1050. pes->stream = ts->stream;
  1051. pes->pid = pid;
  1052. pes->pcr_pid = pcr_pid;
  1053. pes->state = MPEGTS_SKIP;
  1054. pes->pts = AV_NOPTS_VALUE;
  1055. pes->dts = AV_NOPTS_VALUE;
  1056. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  1057. if (!tss) {
  1058. av_free(pes);
  1059. return 0;
  1060. }
  1061. return pes;
  1062. }
  1063. #define MAX_LEVEL 4
  1064. typedef struct {
  1065. AVFormatContext *s;
  1066. AVIOContext pb;
  1067. Mp4Descr *descr;
  1068. Mp4Descr *active_descr;
  1069. int descr_count;
  1070. int max_descr_count;
  1071. int level;
  1072. int predefined_SLConfigDescriptor_seen;
  1073. } MP4DescrParseContext;
  1074. static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
  1075. const uint8_t *buf, unsigned size,
  1076. Mp4Descr *descr, int max_descr_count)
  1077. {
  1078. int ret;
  1079. if (size > (1 << 30))
  1080. return AVERROR_INVALIDDATA;
  1081. if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
  1082. NULL, NULL, NULL, NULL)) < 0)
  1083. return ret;
  1084. d->s = s;
  1085. d->level = 0;
  1086. d->descr_count = 0;
  1087. d->descr = descr;
  1088. d->active_descr = NULL;
  1089. d->max_descr_count = max_descr_count;
  1090. return 0;
  1091. }
  1092. static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
  1093. {
  1094. int64_t new_off = avio_tell(pb);
  1095. (*len) -= new_off - *off;
  1096. *off = new_off;
  1097. }
  1098. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1099. int target_tag);
  1100. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  1101. {
  1102. while (len > 0) {
  1103. int ret = parse_mp4_descr(d, off, len, 0);
  1104. if (ret < 0)
  1105. return ret;
  1106. update_offsets(&d->pb, &off, &len);
  1107. }
  1108. return 0;
  1109. }
  1110. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1111. {
  1112. avio_rb16(&d->pb); // ID
  1113. avio_r8(&d->pb);
  1114. avio_r8(&d->pb);
  1115. avio_r8(&d->pb);
  1116. avio_r8(&d->pb);
  1117. avio_r8(&d->pb);
  1118. update_offsets(&d->pb, &off, &len);
  1119. return parse_mp4_descr_arr(d, off, len);
  1120. }
  1121. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1122. {
  1123. int id_flags;
  1124. if (len < 2)
  1125. return 0;
  1126. id_flags = avio_rb16(&d->pb);
  1127. if (!(id_flags & 0x0020)) { // URL_Flag
  1128. update_offsets(&d->pb, &off, &len);
  1129. return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
  1130. } else {
  1131. return 0;
  1132. }
  1133. }
  1134. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1135. {
  1136. int es_id = 0;
  1137. if (d->descr_count >= d->max_descr_count)
  1138. return AVERROR_INVALIDDATA;
  1139. ff_mp4_parse_es_descr(&d->pb, &es_id);
  1140. d->active_descr = d->descr + (d->descr_count++);
  1141. d->active_descr->es_id = es_id;
  1142. update_offsets(&d->pb, &off, &len);
  1143. parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  1144. update_offsets(&d->pb, &off, &len);
  1145. if (len > 0)
  1146. parse_mp4_descr(d, off, len, MP4SLDescrTag);
  1147. d->active_descr = NULL;
  1148. return 0;
  1149. }
  1150. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
  1151. int len)
  1152. {
  1153. Mp4Descr *descr = d->active_descr;
  1154. if (!descr)
  1155. return AVERROR_INVALIDDATA;
  1156. d->active_descr->dec_config_descr = av_malloc(len);
  1157. if (!descr->dec_config_descr)
  1158. return AVERROR(ENOMEM);
  1159. descr->dec_config_descr_len = len;
  1160. avio_read(&d->pb, descr->dec_config_descr, len);
  1161. return 0;
  1162. }
  1163. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  1164. {
  1165. Mp4Descr *descr = d->active_descr;
  1166. int predefined;
  1167. if (!descr)
  1168. return AVERROR_INVALIDDATA;
  1169. predefined = avio_r8(&d->pb);
  1170. if (!predefined) {
  1171. int lengths;
  1172. int flags = avio_r8(&d->pb);
  1173. descr->sl.use_au_start = !!(flags & 0x80);
  1174. descr->sl.use_au_end = !!(flags & 0x40);
  1175. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  1176. descr->sl.use_padding = !!(flags & 0x08);
  1177. descr->sl.use_timestamps = !!(flags & 0x04);
  1178. descr->sl.use_idle = !!(flags & 0x02);
  1179. descr->sl.timestamp_res = avio_rb32(&d->pb);
  1180. avio_rb32(&d->pb);
  1181. descr->sl.timestamp_len = avio_r8(&d->pb);
  1182. if (descr->sl.timestamp_len > 64) {
  1183. avpriv_request_sample(NULL, "timestamp_len > 64");
  1184. descr->sl.timestamp_len = 64;
  1185. return AVERROR_PATCHWELCOME;
  1186. }
  1187. descr->sl.ocr_len = avio_r8(&d->pb);
  1188. descr->sl.au_len = avio_r8(&d->pb);
  1189. descr->sl.inst_bitrate_len = avio_r8(&d->pb);
  1190. lengths = avio_rb16(&d->pb);
  1191. descr->sl.degr_prior_len = lengths >> 12;
  1192. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  1193. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  1194. } else if (!d->predefined_SLConfigDescriptor_seen){
  1195. avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
  1196. d->predefined_SLConfigDescriptor_seen = 1;
  1197. }
  1198. return 0;
  1199. }
  1200. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  1201. int target_tag)
  1202. {
  1203. int tag;
  1204. int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  1205. update_offsets(&d->pb, &off, &len);
  1206. if (len < 0 || len1 > len || len1 <= 0) {
  1207. av_log(d->s, AV_LOG_ERROR,
  1208. "Tag %x length violation new length %d bytes remaining %d\n",
  1209. tag, len1, len);
  1210. return AVERROR_INVALIDDATA;
  1211. }
  1212. if (d->level++ >= MAX_LEVEL) {
  1213. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  1214. goto done;
  1215. }
  1216. if (target_tag && tag != target_tag) {
  1217. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
  1218. target_tag);
  1219. goto done;
  1220. }
  1221. switch (tag) {
  1222. case MP4IODescrTag:
  1223. parse_MP4IODescrTag(d, off, len1);
  1224. break;
  1225. case MP4ODescrTag:
  1226. parse_MP4ODescrTag(d, off, len1);
  1227. break;
  1228. case MP4ESDescrTag:
  1229. parse_MP4ESDescrTag(d, off, len1);
  1230. break;
  1231. case MP4DecConfigDescrTag:
  1232. parse_MP4DecConfigDescrTag(d, off, len1);
  1233. break;
  1234. case MP4SLDescrTag:
  1235. parse_MP4SLDescrTag(d, off, len1);
  1236. break;
  1237. }
  1238. done:
  1239. d->level--;
  1240. avio_seek(&d->pb, off + len1, SEEK_SET);
  1241. return 0;
  1242. }
  1243. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1244. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1245. {
  1246. MP4DescrParseContext d;
  1247. int ret;
  1248. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1249. if (ret < 0)
  1250. return ret;
  1251. ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1252. *descr_count = d.descr_count;
  1253. return ret;
  1254. }
  1255. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1256. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1257. {
  1258. MP4DescrParseContext d;
  1259. int ret;
  1260. ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
  1261. if (ret < 0)
  1262. return ret;
  1263. ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1264. *descr_count = d.descr_count;
  1265. return ret;
  1266. }
  1267. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
  1268. int section_len)
  1269. {
  1270. MpegTSContext *ts = filter->u.section_filter.opaque;
  1271. SectionHeader h;
  1272. const uint8_t *p, *p_end;
  1273. AVIOContext pb;
  1274. int mp4_descr_count = 0;
  1275. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1276. int i, pid;
  1277. AVFormatContext *s = ts->stream;
  1278. p_end = section + section_len - 4;
  1279. p = section;
  1280. if (parse_section_header(&h, &p, p_end) < 0)
  1281. return;
  1282. if (h.tid != M4OD_TID)
  1283. return;
  1284. mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
  1285. MAX_MP4_DESCR_COUNT);
  1286. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1287. if (!ts->pids[pid])
  1288. continue;
  1289. for (i = 0; i < mp4_descr_count; i++) {
  1290. PESContext *pes;
  1291. AVStream *st;
  1292. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1293. continue;
  1294. if (ts->pids[pid]->type != MPEGTS_PES) {
  1295. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1296. continue;
  1297. }
  1298. pes = ts->pids[pid]->u.pes_filter.opaque;
  1299. st = pes->st;
  1300. if (!st)
  1301. continue;
  1302. pes->sl = mp4_descr[i].sl;
  1303. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1304. mp4_descr[i].dec_config_descr_len, 0,
  1305. NULL, NULL, NULL, NULL);
  1306. ff_mp4_read_dec_config_descr(s, st, &pb);
  1307. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1308. st->codec->extradata_size > 0)
  1309. st->need_parsing = 0;
  1310. if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1311. st->codec->extradata_size > 0)
  1312. st->need_parsing = 0;
  1313. if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1314. // do nothing
  1315. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO)
  1316. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1317. else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
  1318. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1319. else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
  1320. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1321. }
  1322. }
  1323. for (i = 0; i < mp4_descr_count; i++)
  1324. av_free(mp4_descr[i].dec_config_descr);
  1325. }
  1326. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1327. const uint8_t **pp, const uint8_t *desc_list_end,
  1328. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1329. MpegTSContext *ts)
  1330. {
  1331. const uint8_t *desc_end;
  1332. int desc_len, desc_tag, desc_es_id;
  1333. char language[252];
  1334. int i;
  1335. desc_tag = get8(pp, desc_list_end);
  1336. if (desc_tag < 0)
  1337. return AVERROR_INVALIDDATA;
  1338. desc_len = get8(pp, desc_list_end);
  1339. if (desc_len < 0)
  1340. return AVERROR_INVALIDDATA;
  1341. desc_end = *pp + desc_len;
  1342. if (desc_end > desc_list_end)
  1343. return AVERROR_INVALIDDATA;
  1344. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1345. if ((st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
  1346. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1347. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1348. switch (desc_tag) {
  1349. case 0x1E: /* SL descriptor */
  1350. desc_es_id = get16(pp, desc_end);
  1351. if (ts && ts->pids[pid])
  1352. ts->pids[pid]->es_id = desc_es_id;
  1353. for (i = 0; i < mp4_descr_count; i++)
  1354. if (mp4_descr[i].dec_config_descr_len &&
  1355. mp4_descr[i].es_id == desc_es_id) {
  1356. AVIOContext pb;
  1357. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1358. mp4_descr[i].dec_config_descr_len, 0,
  1359. NULL, NULL, NULL, NULL);
  1360. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1361. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1362. st->codec->extradata_size > 0)
  1363. st->need_parsing = 0;
  1364. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1365. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1366. }
  1367. break;
  1368. case 0x1F: /* FMC descriptor */
  1369. get16(pp, desc_end);
  1370. if (mp4_descr_count > 0 &&
  1371. (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe > 0) &&
  1372. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1373. AVIOContext pb;
  1374. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1375. mp4_descr->dec_config_descr_len, 0,
  1376. NULL, NULL, NULL, NULL);
  1377. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1378. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1379. st->codec->extradata_size > 0) {
  1380. st->request_probe = st->need_parsing = 0;
  1381. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1382. }
  1383. }
  1384. break;
  1385. case 0x56: /* DVB teletext descriptor */
  1386. {
  1387. uint8_t *extradata = NULL;
  1388. int language_count = desc_len / 5;
  1389. if (desc_len > 0 && desc_len % 5 != 0)
  1390. return AVERROR_INVALIDDATA;
  1391. if (language_count > 0) {
  1392. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1393. if (language_count > sizeof(language) / 4) {
  1394. language_count = sizeof(language) / 4;
  1395. }
  1396. if (st->codec->extradata == NULL) {
  1397. if (ff_alloc_extradata(st->codec, language_count * 2)) {
  1398. return AVERROR(ENOMEM);
  1399. }
  1400. }
  1401. if (st->codec->extradata_size < language_count * 2)
  1402. return AVERROR_INVALIDDATA;
  1403. extradata = st->codec->extradata;
  1404. for (i = 0; i < language_count; i++) {
  1405. language[i * 4 + 0] = get8(pp, desc_end);
  1406. language[i * 4 + 1] = get8(pp, desc_end);
  1407. language[i * 4 + 2] = get8(pp, desc_end);
  1408. language[i * 4 + 3] = ',';
  1409. memcpy(extradata, *pp, 2);
  1410. extradata += 2;
  1411. *pp += 2;
  1412. }
  1413. language[i * 4 - 1] = 0;
  1414. av_dict_set(&st->metadata, "language", language, 0);
  1415. }
  1416. }
  1417. break;
  1418. case 0x59: /* subtitling descriptor */
  1419. {
  1420. /* 8 bytes per DVB subtitle substream data:
  1421. * ISO_639_language_code (3 bytes),
  1422. * subtitling_type (1 byte),
  1423. * composition_page_id (2 bytes),
  1424. * ancillary_page_id (2 bytes) */
  1425. int language_count = desc_len / 8;
  1426. if (desc_len > 0 && desc_len % 8 != 0)
  1427. return AVERROR_INVALIDDATA;
  1428. if (language_count > 1) {
  1429. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1430. }
  1431. if (language_count > 0) {
  1432. uint8_t *extradata;
  1433. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1434. if (language_count > sizeof(language) / 4) {
  1435. language_count = sizeof(language) / 4;
  1436. }
  1437. if (st->codec->extradata == NULL) {
  1438. if (ff_alloc_extradata(st->codec, language_count * 5)) {
  1439. return AVERROR(ENOMEM);
  1440. }
  1441. }
  1442. if (st->codec->extradata_size < language_count * 5)
  1443. return AVERROR_INVALIDDATA;
  1444. extradata = st->codec->extradata;
  1445. for (i = 0; i < language_count; i++) {
  1446. language[i * 4 + 0] = get8(pp, desc_end);
  1447. language[i * 4 + 1] = get8(pp, desc_end);
  1448. language[i * 4 + 2] = get8(pp, desc_end);
  1449. language[i * 4 + 3] = ',';
  1450. /* hearing impaired subtitles detection using subtitling_type */
  1451. switch (*pp[0]) {
  1452. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1453. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1454. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1455. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1456. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1457. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1458. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1459. break;
  1460. }
  1461. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1462. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1463. extradata += 5;
  1464. *pp += 4;
  1465. }
  1466. language[i * 4 - 1] = 0;
  1467. av_dict_set(&st->metadata, "language", language, 0);
  1468. }
  1469. }
  1470. break;
  1471. case 0x0a: /* ISO 639 language descriptor */
  1472. for (i = 0; i + 4 <= desc_len; i += 4) {
  1473. language[i + 0] = get8(pp, desc_end);
  1474. language[i + 1] = get8(pp, desc_end);
  1475. language[i + 2] = get8(pp, desc_end);
  1476. language[i + 3] = ',';
  1477. switch (get8(pp, desc_end)) {
  1478. case 0x01:
  1479. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1480. break;
  1481. case 0x02:
  1482. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1483. break;
  1484. case 0x03:
  1485. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1486. break;
  1487. }
  1488. }
  1489. if (i && language[0]) {
  1490. language[i - 1] = 0;
  1491. av_dict_set(&st->metadata, "language", language, 0);
  1492. }
  1493. break;
  1494. case 0x05: /* registration descriptor */
  1495. st->codec->codec_tag = bytestream_get_le32(pp);
  1496. av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
  1497. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1498. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1499. break;
  1500. case 0x52: /* stream identifier descriptor */
  1501. st->stream_identifier = 1 + get8(pp, desc_end);
  1502. break;
  1503. case 0x26: /* metadata descriptor */
  1504. if (get16(pp, desc_end) == 0xFFFF)
  1505. *pp += 4;
  1506. if (get8(pp, desc_end) == 0xFF) {
  1507. st->codec->codec_tag = bytestream_get_le32(pp);
  1508. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1509. mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
  1510. }
  1511. break;
  1512. default:
  1513. break;
  1514. }
  1515. *pp = desc_end;
  1516. return 0;
  1517. }
  1518. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1519. {
  1520. MpegTSContext *ts = filter->u.section_filter.opaque;
  1521. SectionHeader h1, *h = &h1;
  1522. PESContext *pes;
  1523. AVStream *st;
  1524. const uint8_t *p, *p_end, *desc_list_end;
  1525. int program_info_length, pcr_pid, pid, stream_type;
  1526. int desc_list_len;
  1527. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1528. int mp4_descr_count = 0;
  1529. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1530. int i;
  1531. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1532. hex_dump_debug(ts->stream, section, section_len);
  1533. p_end = section + section_len - 4;
  1534. p = section;
  1535. if (parse_section_header(h, &p, p_end) < 0)
  1536. return;
  1537. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1538. h->id, h->sec_num, h->last_sec_num);
  1539. if (h->tid != PMT_TID)
  1540. return;
  1541. if (ts->skip_changes)
  1542. return;
  1543. clear_program(ts, h->id);
  1544. pcr_pid = get16(&p, p_end);
  1545. if (pcr_pid < 0)
  1546. return;
  1547. pcr_pid &= 0x1fff;
  1548. add_pid_to_pmt(ts, h->id, pcr_pid);
  1549. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1550. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1551. program_info_length = get16(&p, p_end);
  1552. if (program_info_length < 0)
  1553. return;
  1554. program_info_length &= 0xfff;
  1555. while (program_info_length >= 2) {
  1556. uint8_t tag, len;
  1557. tag = get8(&p, p_end);
  1558. len = get8(&p, p_end);
  1559. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1560. if (len > program_info_length - 2)
  1561. // something else is broken, exit the program_descriptors_loop
  1562. break;
  1563. program_info_length -= len + 2;
  1564. if (tag == 0x1d) { // IOD descriptor
  1565. get8(&p, p_end); // scope
  1566. get8(&p, p_end); // label
  1567. len -= 2;
  1568. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1569. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1570. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1571. prog_reg_desc = bytestream_get_le32(&p);
  1572. len -= 4;
  1573. }
  1574. p += len;
  1575. }
  1576. p += program_info_length;
  1577. if (p >= p_end)
  1578. goto out;
  1579. // stop parsing after pmt, we found header
  1580. if (!ts->stream->nb_streams)
  1581. ts->stop_parse = 2;
  1582. set_pmt_found(ts, h->id);
  1583. for (;;) {
  1584. st = 0;
  1585. pes = NULL;
  1586. stream_type = get8(&p, p_end);
  1587. if (stream_type < 0)
  1588. break;
  1589. pid = get16(&p, p_end);
  1590. if (pid < 0)
  1591. goto out;
  1592. pid &= 0x1fff;
  1593. if (pid == ts->current_pid)
  1594. goto out;
  1595. /* now create stream */
  1596. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1597. pes = ts->pids[pid]->u.pes_filter.opaque;
  1598. if (!pes->st) {
  1599. pes->st = avformat_new_stream(pes->stream, NULL);
  1600. if (!pes->st)
  1601. goto out;
  1602. pes->st->id = pes->pid;
  1603. }
  1604. st = pes->st;
  1605. } else if (stream_type != 0x13) {
  1606. if (ts->pids[pid])
  1607. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1608. pes = add_pes_stream(ts, pid, pcr_pid);
  1609. if (pes) {
  1610. st = avformat_new_stream(pes->stream, NULL);
  1611. if (!st)
  1612. goto out;
  1613. st->id = pes->pid;
  1614. }
  1615. } else {
  1616. int idx = ff_find_stream_index(ts->stream, pid);
  1617. if (idx >= 0) {
  1618. st = ts->stream->streams[idx];
  1619. } else {
  1620. st = avformat_new_stream(ts->stream, NULL);
  1621. if (!st)
  1622. goto out;
  1623. st->id = pid;
  1624. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1625. }
  1626. }
  1627. if (!st)
  1628. goto out;
  1629. if (pes && !pes->stream_type)
  1630. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1631. add_pid_to_pmt(ts, h->id, pid);
  1632. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1633. desc_list_len = get16(&p, p_end);
  1634. if (desc_list_len < 0)
  1635. goto out;
  1636. desc_list_len &= 0xfff;
  1637. desc_list_end = p + desc_list_len;
  1638. if (desc_list_end > p_end)
  1639. goto out;
  1640. for (;;) {
  1641. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1642. desc_list_end, mp4_descr,
  1643. mp4_descr_count, pid, ts) < 0)
  1644. break;
  1645. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1646. stream_type == 0x83 && pes->sub_st) {
  1647. ff_program_add_stream_index(ts->stream, h->id,
  1648. pes->sub_st->index);
  1649. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1650. }
  1651. }
  1652. p = desc_list_end;
  1653. }
  1654. if (!ts->pids[pcr_pid])
  1655. mpegts_open_pcr_filter(ts, pcr_pid);
  1656. out:
  1657. for (i = 0; i < mp4_descr_count; i++)
  1658. av_free(mp4_descr[i].dec_config_descr);
  1659. }
  1660. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1661. {
  1662. MpegTSContext *ts = filter->u.section_filter.opaque;
  1663. SectionHeader h1, *h = &h1;
  1664. const uint8_t *p, *p_end;
  1665. int sid, pmt_pid;
  1666. AVProgram *program;
  1667. av_dlog(ts->stream, "PAT:\n");
  1668. hex_dump_debug(ts->stream, section, section_len);
  1669. p_end = section + section_len - 4;
  1670. p = section;
  1671. if (parse_section_header(h, &p, p_end) < 0)
  1672. return;
  1673. if (h->tid != PAT_TID)
  1674. return;
  1675. if (ts->skip_changes)
  1676. return;
  1677. ts->stream->ts_id = h->id;
  1678. clear_programs(ts);
  1679. for (;;) {
  1680. sid = get16(&p, p_end);
  1681. if (sid < 0)
  1682. break;
  1683. pmt_pid = get16(&p, p_end);
  1684. if (pmt_pid < 0)
  1685. break;
  1686. pmt_pid &= 0x1fff;
  1687. if (pmt_pid == ts->current_pid)
  1688. break;
  1689. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1690. if (sid == 0x0000) {
  1691. /* NIT info */
  1692. } else {
  1693. MpegTSFilter *fil = ts->pids[pmt_pid];
  1694. program = av_new_program(ts->stream, sid);
  1695. program->program_num = sid;
  1696. program->pmt_pid = pmt_pid;
  1697. if (fil)
  1698. if ( fil->type != MPEGTS_SECTION
  1699. || fil->pid != pmt_pid
  1700. || fil->u.section_filter.section_cb != pmt_cb)
  1701. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1702. if (!ts->pids[pmt_pid])
  1703. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1704. add_pat_entry(ts, sid);
  1705. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1706. add_pid_to_pmt(ts, sid, pmt_pid);
  1707. }
  1708. }
  1709. if (sid < 0) {
  1710. int i,j;
  1711. for (j=0; j<ts->stream->nb_programs; j++) {
  1712. for (i = 0; i < ts->nb_prg; i++)
  1713. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1714. break;
  1715. if (i==ts->nb_prg && !ts->skip_clear)
  1716. clear_avprogram(ts, ts->stream->programs[j]->id);
  1717. }
  1718. }
  1719. }
  1720. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1721. {
  1722. MpegTSContext *ts = filter->u.section_filter.opaque;
  1723. SectionHeader h1, *h = &h1;
  1724. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1725. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1726. char *name, *provider_name;
  1727. av_dlog(ts->stream, "SDT:\n");
  1728. hex_dump_debug(ts->stream, section, section_len);
  1729. p_end = section + section_len - 4;
  1730. p = section;
  1731. if (parse_section_header(h, &p, p_end) < 0)
  1732. return;
  1733. if (h->tid != SDT_TID)
  1734. return;
  1735. if (ts->skip_changes)
  1736. return;
  1737. onid = get16(&p, p_end);
  1738. if (onid < 0)
  1739. return;
  1740. val = get8(&p, p_end);
  1741. if (val < 0)
  1742. return;
  1743. for (;;) {
  1744. sid = get16(&p, p_end);
  1745. if (sid < 0)
  1746. break;
  1747. val = get8(&p, p_end);
  1748. if (val < 0)
  1749. break;
  1750. desc_list_len = get16(&p, p_end);
  1751. if (desc_list_len < 0)
  1752. break;
  1753. desc_list_len &= 0xfff;
  1754. desc_list_end = p + desc_list_len;
  1755. if (desc_list_end > p_end)
  1756. break;
  1757. for (;;) {
  1758. desc_tag = get8(&p, desc_list_end);
  1759. if (desc_tag < 0)
  1760. break;
  1761. desc_len = get8(&p, desc_list_end);
  1762. desc_end = p + desc_len;
  1763. if (desc_end > desc_list_end)
  1764. break;
  1765. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1766. desc_tag, desc_len);
  1767. switch (desc_tag) {
  1768. case 0x48:
  1769. service_type = get8(&p, p_end);
  1770. if (service_type < 0)
  1771. break;
  1772. provider_name = getstr8(&p, p_end);
  1773. if (!provider_name)
  1774. break;
  1775. name = getstr8(&p, p_end);
  1776. if (name) {
  1777. AVProgram *program = av_new_program(ts->stream, sid);
  1778. if (program) {
  1779. av_dict_set(&program->metadata, "service_name", name, 0);
  1780. av_dict_set(&program->metadata, "service_provider",
  1781. provider_name, 0);
  1782. }
  1783. }
  1784. av_free(name);
  1785. av_free(provider_name);
  1786. break;
  1787. default:
  1788. break;
  1789. }
  1790. p = desc_end;
  1791. }
  1792. p = desc_list_end;
  1793. }
  1794. }
  1795. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1796. const uint8_t *packet);
  1797. /* handle one TS packet */
  1798. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1799. {
  1800. MpegTSFilter *tss;
  1801. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1802. has_adaptation, has_payload;
  1803. const uint8_t *p, *p_end;
  1804. int64_t pos;
  1805. pid = AV_RB16(packet + 1) & 0x1fff;
  1806. if (pid && discard_pid(ts, pid))
  1807. return 0;
  1808. is_start = packet[1] & 0x40;
  1809. tss = ts->pids[pid];
  1810. if (ts->auto_guess && !tss && is_start) {
  1811. add_pes_stream(ts, pid, -1);
  1812. tss = ts->pids[pid];
  1813. }
  1814. if (!tss)
  1815. return 0;
  1816. ts->current_pid = pid;
  1817. afc = (packet[3] >> 4) & 3;
  1818. if (afc == 0) /* reserved value */
  1819. return 0;
  1820. has_adaptation = afc & 2;
  1821. has_payload = afc & 1;
  1822. is_discontinuity = has_adaptation &&
  1823. packet[4] != 0 && /* with length > 0 */
  1824. (packet[5] & 0x80); /* and discontinuity indicated */
  1825. /* continuity check (currently not used) */
  1826. cc = (packet[3] & 0xf);
  1827. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1828. cc_ok = pid == 0x1FFF || // null packet PID
  1829. is_discontinuity ||
  1830. tss->last_cc < 0 ||
  1831. expected_cc == cc;
  1832. tss->last_cc = cc;
  1833. if (!cc_ok) {
  1834. av_log(ts->stream, AV_LOG_DEBUG,
  1835. "Continuity check failed for pid %d expected %d got %d\n",
  1836. pid, expected_cc, cc);
  1837. if (tss->type == MPEGTS_PES) {
  1838. PESContext *pc = tss->u.pes_filter.opaque;
  1839. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1840. }
  1841. }
  1842. p = packet + 4;
  1843. if (has_adaptation) {
  1844. int64_t pcr_h;
  1845. int pcr_l;
  1846. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1847. tss->last_pcr = pcr_h * 300 + pcr_l;
  1848. /* skip adaptation field */
  1849. p += p[0] + 1;
  1850. }
  1851. /* if past the end of packet, ignore */
  1852. p_end = packet + TS_PACKET_SIZE;
  1853. if (p >= p_end || !has_payload)
  1854. return 0;
  1855. pos = avio_tell(ts->stream->pb);
  1856. if (pos >= 0) {
  1857. av_assert0(pos >= TS_PACKET_SIZE);
  1858. ts->pos47_full = pos - TS_PACKET_SIZE;
  1859. }
  1860. if (tss->type == MPEGTS_SECTION) {
  1861. if (is_start) {
  1862. /* pointer field present */
  1863. len = *p++;
  1864. if (p + len > p_end)
  1865. return 0;
  1866. if (len && cc_ok) {
  1867. /* write remaining section bytes */
  1868. write_section_data(ts, tss,
  1869. p, len, 0);
  1870. /* check whether filter has been closed */
  1871. if (!ts->pids[pid])
  1872. return 0;
  1873. }
  1874. p += len;
  1875. if (p < p_end) {
  1876. write_section_data(ts, tss,
  1877. p, p_end - p, 1);
  1878. }
  1879. } else {
  1880. if (cc_ok) {
  1881. write_section_data(ts, tss,
  1882. p, p_end - p, 0);
  1883. }
  1884. }
  1885. // stop find_stream_info from waiting for more streams
  1886. // when all programs have received a PMT
  1887. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER) {
  1888. int i;
  1889. for (i = 0; i < ts->nb_prg; i++) {
  1890. if (!ts->prg[i].pmt_found)
  1891. break;
  1892. }
  1893. if (i == ts->nb_prg && ts->nb_prg > 0) {
  1894. if (ts->stream->nb_streams > 1 || pos > 100000) {
  1895. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  1896. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1897. }
  1898. }
  1899. }
  1900. } else {
  1901. int ret;
  1902. // Note: The position here points actually behind the current packet.
  1903. if (tss->type == MPEGTS_PES) {
  1904. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1905. pos - ts->raw_packet_size)) < 0)
  1906. return ret;
  1907. }
  1908. }
  1909. return 0;
  1910. }
  1911. static void reanalyze(MpegTSContext *ts) {
  1912. AVIOContext *pb = ts->stream->pb;
  1913. int64_t pos = avio_tell(pb);
  1914. if (pos < 0)
  1915. return;
  1916. pos -= ts->pos47_full;
  1917. if (pos == TS_PACKET_SIZE) {
  1918. ts->size_stat[0] ++;
  1919. } else if (pos == TS_DVHS_PACKET_SIZE) {
  1920. ts->size_stat[1] ++;
  1921. } else if (pos == TS_FEC_PACKET_SIZE) {
  1922. ts->size_stat[2] ++;
  1923. }
  1924. ts->size_stat_count ++;
  1925. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  1926. int newsize = 0;
  1927. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  1928. newsize = TS_PACKET_SIZE;
  1929. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  1930. newsize = TS_DVHS_PACKET_SIZE;
  1931. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  1932. newsize = TS_FEC_PACKET_SIZE;
  1933. }
  1934. if (newsize && newsize != ts->raw_packet_size) {
  1935. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  1936. ts->raw_packet_size = newsize;
  1937. }
  1938. ts->size_stat_count = 0;
  1939. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  1940. }
  1941. }
  1942. /* XXX: try to find a better synchro over several packets (use
  1943. * get_packet_size() ?) */
  1944. static int mpegts_resync(AVFormatContext *s)
  1945. {
  1946. MpegTSContext *ts = s->priv_data;
  1947. AVIOContext *pb = s->pb;
  1948. int c, i;
  1949. for (i = 0; i < ts->resync_size; i++) {
  1950. c = avio_r8(pb);
  1951. if (avio_feof(pb))
  1952. return AVERROR_EOF;
  1953. if (c == 0x47) {
  1954. avio_seek(pb, -1, SEEK_CUR);
  1955. reanalyze(s->priv_data);
  1956. return 0;
  1957. }
  1958. }
  1959. av_log(s, AV_LOG_ERROR,
  1960. "max resync size reached, could not find sync byte\n");
  1961. /* no sync found */
  1962. return AVERROR_INVALIDDATA;
  1963. }
  1964. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  1965. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  1966. const uint8_t **data)
  1967. {
  1968. AVIOContext *pb = s->pb;
  1969. int len;
  1970. for (;;) {
  1971. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  1972. if (len != TS_PACKET_SIZE)
  1973. return len < 0 ? len : AVERROR_EOF;
  1974. /* check packet sync byte */
  1975. if ((*data)[0] != 0x47) {
  1976. /* find a new packet start */
  1977. uint64_t pos = avio_tell(pb);
  1978. avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
  1979. if (mpegts_resync(s) < 0)
  1980. return AVERROR(EAGAIN);
  1981. else
  1982. continue;
  1983. } else {
  1984. break;
  1985. }
  1986. }
  1987. return 0;
  1988. }
  1989. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  1990. {
  1991. AVIOContext *pb = s->pb;
  1992. int skip = raw_packet_size - TS_PACKET_SIZE;
  1993. if (skip > 0)
  1994. avio_skip(pb, skip);
  1995. }
  1996. static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
  1997. {
  1998. AVFormatContext *s = ts->stream;
  1999. uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  2000. const uint8_t *data;
  2001. int64_t packet_num;
  2002. int ret = 0;
  2003. if (avio_tell(s->pb) != ts->last_pos) {
  2004. int i;
  2005. av_dlog(ts->stream, "Skipping after seek\n");
  2006. /* seek detected, flush pes buffer */
  2007. for (i = 0; i < NB_PID_MAX; i++) {
  2008. if (ts->pids[i]) {
  2009. if (ts->pids[i]->type == MPEGTS_PES) {
  2010. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2011. av_buffer_unref(&pes->buffer);
  2012. pes->data_index = 0;
  2013. pes->state = MPEGTS_SKIP; /* skip until pes header */
  2014. }
  2015. ts->pids[i]->last_cc = -1;
  2016. ts->pids[i]->last_pcr = -1;
  2017. }
  2018. }
  2019. }
  2020. ts->stop_parse = 0;
  2021. packet_num = 0;
  2022. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2023. for (;;) {
  2024. packet_num++;
  2025. if (nb_packets != 0 && packet_num >= nb_packets ||
  2026. ts->stop_parse > 1) {
  2027. ret = AVERROR(EAGAIN);
  2028. break;
  2029. }
  2030. if (ts->stop_parse > 0)
  2031. break;
  2032. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2033. if (ret != 0)
  2034. break;
  2035. ret = handle_packet(ts, data);
  2036. finished_reading_packet(s, ts->raw_packet_size);
  2037. if (ret != 0)
  2038. break;
  2039. }
  2040. ts->last_pos = avio_tell(s->pb);
  2041. return ret;
  2042. }
  2043. static int mpegts_probe(AVProbeData *p)
  2044. {
  2045. const int size = p->buf_size;
  2046. int maxscore = 0;
  2047. int sumscore = 0;
  2048. int i;
  2049. int check_count = size / TS_FEC_PACKET_SIZE;
  2050. #define CHECK_COUNT 10
  2051. #define CHECK_BLOCK 100
  2052. if (check_count < CHECK_COUNT)
  2053. return AVERROR_INVALIDDATA;
  2054. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2055. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2056. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
  2057. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  2058. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  2059. score = FFMAX3(score, dvhs_score, fec_score);
  2060. sumscore += score;
  2061. maxscore = FFMAX(maxscore, score);
  2062. }
  2063. sumscore = sumscore * CHECK_COUNT / check_count;
  2064. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2065. av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2066. if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2067. else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2068. else
  2069. return AVERROR_INVALIDDATA;
  2070. }
  2071. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2072. * (-1) if not available */
  2073. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2074. {
  2075. int afc, len, flags;
  2076. const uint8_t *p;
  2077. unsigned int v;
  2078. afc = (packet[3] >> 4) & 3;
  2079. if (afc <= 1)
  2080. return AVERROR_INVALIDDATA;
  2081. p = packet + 4;
  2082. len = p[0];
  2083. p++;
  2084. if (len == 0)
  2085. return AVERROR_INVALIDDATA;
  2086. flags = *p++;
  2087. len--;
  2088. if (!(flags & 0x10))
  2089. return AVERROR_INVALIDDATA;
  2090. if (len < 6)
  2091. return AVERROR_INVALIDDATA;
  2092. v = AV_RB32(p);
  2093. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2094. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2095. return 0;
  2096. }
  2097. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2098. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2099. * probe buffer usually is big enough. Only warn if the seek failed
  2100. * on files where the seek should work. */
  2101. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2102. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2103. }
  2104. static int mpegts_read_header(AVFormatContext *s)
  2105. {
  2106. MpegTSContext *ts = s->priv_data;
  2107. AVIOContext *pb = s->pb;
  2108. uint8_t buf[8 * 1024] = {0};
  2109. int len;
  2110. int64_t pos, probesize = s->probesize ? s->probesize : s->probesize2;
  2111. ffio_ensure_seekback(pb, probesize);
  2112. /* read the first 8192 bytes to get packet size */
  2113. pos = avio_tell(pb);
  2114. len = avio_read(pb, buf, sizeof(buf));
  2115. ts->raw_packet_size = get_packet_size(buf, len);
  2116. if (ts->raw_packet_size <= 0) {
  2117. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2118. ts->raw_packet_size = TS_PACKET_SIZE;
  2119. }
  2120. ts->stream = s;
  2121. ts->auto_guess = 0;
  2122. if (s->iformat == &ff_mpegts_demuxer) {
  2123. /* normal demux */
  2124. /* first do a scan to get all the services */
  2125. seek_back(s, pb, pos);
  2126. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2127. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2128. handle_packets(ts, probesize / ts->raw_packet_size);
  2129. /* if could not find service, enable auto_guess */
  2130. ts->auto_guess = 1;
  2131. av_dlog(ts->stream, "tuning done\n");
  2132. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2133. } else {
  2134. AVStream *st;
  2135. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2136. int64_t pcrs[2], pcr_h;
  2137. int packet_count[2];
  2138. uint8_t packet[TS_PACKET_SIZE];
  2139. const uint8_t *data;
  2140. /* only read packets */
  2141. st = avformat_new_stream(s, NULL);
  2142. if (!st)
  2143. return AVERROR(ENOMEM);
  2144. avpriv_set_pts_info(st, 60, 1, 27000000);
  2145. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2146. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  2147. /* we iterate until we find two PCRs to estimate the bitrate */
  2148. pcr_pid = -1;
  2149. nb_pcrs = 0;
  2150. nb_packets = 0;
  2151. for (;;) {
  2152. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2153. if (ret < 0)
  2154. return ret;
  2155. pid = AV_RB16(data + 1) & 0x1fff;
  2156. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2157. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2158. finished_reading_packet(s, ts->raw_packet_size);
  2159. pcr_pid = pid;
  2160. packet_count[nb_pcrs] = nb_packets;
  2161. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2162. nb_pcrs++;
  2163. if (nb_pcrs >= 2)
  2164. break;
  2165. } else {
  2166. finished_reading_packet(s, ts->raw_packet_size);
  2167. }
  2168. nb_packets++;
  2169. }
  2170. /* NOTE1: the bitrate is computed without the FEC */
  2171. /* NOTE2: it is only the bitrate of the start of the stream */
  2172. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2173. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2174. s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
  2175. st->codec->bit_rate = s->bit_rate;
  2176. st->start_time = ts->cur_pcr;
  2177. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  2178. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2179. }
  2180. seek_back(s, pb, pos);
  2181. return 0;
  2182. }
  2183. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2184. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2185. {
  2186. MpegTSContext *ts = s->priv_data;
  2187. int ret, i;
  2188. int64_t pcr_h, next_pcr_h, pos;
  2189. int pcr_l, next_pcr_l;
  2190. uint8_t pcr_buf[12];
  2191. const uint8_t *data;
  2192. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2193. return AVERROR(ENOMEM);
  2194. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2195. pkt->pos = avio_tell(s->pb);
  2196. if (ret < 0) {
  2197. av_free_packet(pkt);
  2198. return ret;
  2199. }
  2200. if (data != pkt->data)
  2201. memcpy(pkt->data, data, ts->raw_packet_size);
  2202. finished_reading_packet(s, ts->raw_packet_size);
  2203. if (ts->mpeg2ts_compute_pcr) {
  2204. /* compute exact PCR for each packet */
  2205. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2206. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2207. pos = avio_tell(s->pb);
  2208. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2209. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2210. avio_read(s->pb, pcr_buf, 12);
  2211. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2212. /* XXX: not precise enough */
  2213. ts->pcr_incr =
  2214. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2215. (i + 1);
  2216. break;
  2217. }
  2218. }
  2219. avio_seek(s->pb, pos, SEEK_SET);
  2220. /* no next PCR found: we use previous increment */
  2221. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2222. }
  2223. pkt->pts = ts->cur_pcr;
  2224. pkt->duration = ts->pcr_incr;
  2225. ts->cur_pcr += ts->pcr_incr;
  2226. }
  2227. pkt->stream_index = 0;
  2228. return 0;
  2229. }
  2230. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2231. {
  2232. MpegTSContext *ts = s->priv_data;
  2233. int ret, i;
  2234. pkt->size = -1;
  2235. ts->pkt = pkt;
  2236. ret = handle_packets(ts, 0);
  2237. if (ret < 0) {
  2238. av_free_packet(ts->pkt);
  2239. /* flush pes data left */
  2240. for (i = 0; i < NB_PID_MAX; i++)
  2241. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2242. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2243. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2244. new_pes_packet(pes, pkt);
  2245. pes->state = MPEGTS_SKIP;
  2246. ret = 0;
  2247. break;
  2248. }
  2249. }
  2250. }
  2251. if (!ret && pkt->size < 0)
  2252. ret = AVERROR(EINTR);
  2253. return ret;
  2254. }
  2255. static void mpegts_free(MpegTSContext *ts)
  2256. {
  2257. int i;
  2258. clear_programs(ts);
  2259. for (i = 0; i < NB_PID_MAX; i++)
  2260. if (ts->pids[i])
  2261. mpegts_close_filter(ts, ts->pids[i]);
  2262. }
  2263. static int mpegts_read_close(AVFormatContext *s)
  2264. {
  2265. MpegTSContext *ts = s->priv_data;
  2266. mpegts_free(ts);
  2267. return 0;
  2268. }
  2269. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2270. int64_t *ppos, int64_t pos_limit)
  2271. {
  2272. MpegTSContext *ts = s->priv_data;
  2273. int64_t pos, timestamp;
  2274. uint8_t buf[TS_PACKET_SIZE];
  2275. int pcr_l, pcr_pid =
  2276. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2277. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2278. pos =
  2279. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2280. ts->raw_packet_size + pos47;
  2281. while(pos < pos_limit) {
  2282. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2283. return AV_NOPTS_VALUE;
  2284. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2285. return AV_NOPTS_VALUE;
  2286. if (buf[0] != 0x47) {
  2287. avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
  2288. if (mpegts_resync(s) < 0)
  2289. return AV_NOPTS_VALUE;
  2290. pos = avio_tell(s->pb);
  2291. continue;
  2292. }
  2293. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2294. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2295. *ppos = pos;
  2296. return timestamp;
  2297. }
  2298. pos += ts->raw_packet_size;
  2299. }
  2300. return AV_NOPTS_VALUE;
  2301. }
  2302. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2303. int64_t *ppos, int64_t pos_limit)
  2304. {
  2305. MpegTSContext *ts = s->priv_data;
  2306. int64_t pos;
  2307. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2308. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2309. ff_read_frame_flush(s);
  2310. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2311. return AV_NOPTS_VALUE;
  2312. while(pos < pos_limit) {
  2313. int ret;
  2314. AVPacket pkt;
  2315. av_init_packet(&pkt);
  2316. ret = av_read_frame(s, &pkt);
  2317. if (ret < 0)
  2318. return AV_NOPTS_VALUE;
  2319. av_free_packet(&pkt);
  2320. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2321. ff_reduce_index(s, pkt.stream_index);
  2322. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2323. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2324. *ppos = pkt.pos;
  2325. return pkt.dts;
  2326. }
  2327. }
  2328. pos = pkt.pos;
  2329. }
  2330. return AV_NOPTS_VALUE;
  2331. }
  2332. /**************************************************************/
  2333. /* parsing functions - called from other demuxers such as RTP */
  2334. MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
  2335. {
  2336. MpegTSContext *ts;
  2337. ts = av_mallocz(sizeof(MpegTSContext));
  2338. if (!ts)
  2339. return NULL;
  2340. /* no stream case, currently used by RTP */
  2341. ts->raw_packet_size = TS_PACKET_SIZE;
  2342. ts->stream = s;
  2343. ts->auto_guess = 1;
  2344. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2345. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2346. return ts;
  2347. }
  2348. /* return the consumed length if a packet was output, or -1 if no
  2349. * packet is output */
  2350. int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2351. const uint8_t *buf, int len)
  2352. {
  2353. int len1;
  2354. len1 = len;
  2355. ts->pkt = pkt;
  2356. for (;;) {
  2357. ts->stop_parse = 0;
  2358. if (len < TS_PACKET_SIZE)
  2359. return AVERROR_INVALIDDATA;
  2360. if (buf[0] != 0x47) {
  2361. buf++;
  2362. len--;
  2363. } else {
  2364. handle_packet(ts, buf);
  2365. buf += TS_PACKET_SIZE;
  2366. len -= TS_PACKET_SIZE;
  2367. if (ts->stop_parse == 1)
  2368. break;
  2369. }
  2370. }
  2371. return len1 - len;
  2372. }
  2373. void avpriv_mpegts_parse_close(MpegTSContext *ts)
  2374. {
  2375. mpegts_free(ts);
  2376. av_free(ts);
  2377. }
  2378. AVInputFormat ff_mpegts_demuxer = {
  2379. .name = "mpegts",
  2380. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2381. .priv_data_size = sizeof(MpegTSContext),
  2382. .read_probe = mpegts_probe,
  2383. .read_header = mpegts_read_header,
  2384. .read_packet = mpegts_read_packet,
  2385. .read_close = mpegts_read_close,
  2386. .read_timestamp = mpegts_get_dts,
  2387. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2388. .priv_class = &mpegts_class,
  2389. };
  2390. AVInputFormat ff_mpegtsraw_demuxer = {
  2391. .name = "mpegtsraw",
  2392. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2393. .priv_data_size = sizeof(MpegTSContext),
  2394. .read_header = mpegts_read_header,
  2395. .read_packet = mpegts_raw_read_packet,
  2396. .read_close = mpegts_read_close,
  2397. .read_timestamp = mpegts_get_dts,
  2398. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2399. .priv_class = &mpegtsraw_class,
  2400. };