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.

2736 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 || st->request_probe > 0) &&
  1381. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1382. AVIOContext pb;
  1383. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1384. mp4_descr->dec_config_descr_len, 0,
  1385. NULL, NULL, NULL, NULL);
  1386. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1387. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1388. st->codec->extradata_size > 0) {
  1389. st->request_probe = st->need_parsing = 0;
  1390. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1391. }
  1392. }
  1393. break;
  1394. case 0x56: /* DVB teletext descriptor */
  1395. {
  1396. uint8_t *extradata = NULL;
  1397. int language_count = desc_len / 5;
  1398. if (desc_len > 0 && desc_len % 5 != 0)
  1399. return AVERROR_INVALIDDATA;
  1400. if (language_count > 0) {
  1401. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1402. if (language_count > sizeof(language) / 4) {
  1403. language_count = sizeof(language) / 4;
  1404. }
  1405. if (st->codec->extradata == NULL) {
  1406. if (ff_alloc_extradata(st->codec, language_count * 2)) {
  1407. return AVERROR(ENOMEM);
  1408. }
  1409. }
  1410. if (st->codec->extradata_size < language_count * 2)
  1411. return AVERROR_INVALIDDATA;
  1412. extradata = st->codec->extradata;
  1413. for (i = 0; i < language_count; i++) {
  1414. language[i * 4 + 0] = get8(pp, desc_end);
  1415. language[i * 4 + 1] = get8(pp, desc_end);
  1416. language[i * 4 + 2] = get8(pp, desc_end);
  1417. language[i * 4 + 3] = ',';
  1418. memcpy(extradata, *pp, 2);
  1419. extradata += 2;
  1420. *pp += 2;
  1421. }
  1422. language[i * 4 - 1] = 0;
  1423. av_dict_set(&st->metadata, "language", language, 0);
  1424. }
  1425. }
  1426. break;
  1427. case 0x59: /* subtitling descriptor */
  1428. {
  1429. /* 8 bytes per DVB subtitle substream data:
  1430. * ISO_639_language_code (3 bytes),
  1431. * subtitling_type (1 byte),
  1432. * composition_page_id (2 bytes),
  1433. * ancillary_page_id (2 bytes) */
  1434. int language_count = desc_len / 8;
  1435. if (desc_len > 0 && desc_len % 8 != 0)
  1436. return AVERROR_INVALIDDATA;
  1437. if (language_count > 1) {
  1438. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1439. }
  1440. if (language_count > 0) {
  1441. uint8_t *extradata;
  1442. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1443. if (language_count > sizeof(language) / 4) {
  1444. language_count = sizeof(language) / 4;
  1445. }
  1446. if (st->codec->extradata == NULL) {
  1447. if (ff_alloc_extradata(st->codec, language_count * 5)) {
  1448. return AVERROR(ENOMEM);
  1449. }
  1450. }
  1451. if (st->codec->extradata_size < language_count * 5)
  1452. return AVERROR_INVALIDDATA;
  1453. extradata = st->codec->extradata;
  1454. for (i = 0; i < language_count; i++) {
  1455. language[i * 4 + 0] = get8(pp, desc_end);
  1456. language[i * 4 + 1] = get8(pp, desc_end);
  1457. language[i * 4 + 2] = get8(pp, desc_end);
  1458. language[i * 4 + 3] = ',';
  1459. /* hearing impaired subtitles detection using subtitling_type */
  1460. switch (*pp[0]) {
  1461. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1462. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1463. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1464. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1465. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1466. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1467. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1468. break;
  1469. }
  1470. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1471. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1472. extradata += 5;
  1473. *pp += 4;
  1474. }
  1475. language[i * 4 - 1] = 0;
  1476. av_dict_set(&st->metadata, "language", language, 0);
  1477. }
  1478. }
  1479. break;
  1480. case 0x0a: /* ISO 639 language descriptor */
  1481. for (i = 0; i + 4 <= desc_len; i += 4) {
  1482. language[i + 0] = get8(pp, desc_end);
  1483. language[i + 1] = get8(pp, desc_end);
  1484. language[i + 2] = get8(pp, desc_end);
  1485. language[i + 3] = ',';
  1486. switch (get8(pp, desc_end)) {
  1487. case 0x01:
  1488. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1489. break;
  1490. case 0x02:
  1491. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1492. break;
  1493. case 0x03:
  1494. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1495. break;
  1496. }
  1497. }
  1498. if (i && language[0]) {
  1499. language[i - 1] = 0;
  1500. av_dict_set(&st->metadata, "language", language, 0);
  1501. }
  1502. break;
  1503. case 0x05: /* registration descriptor */
  1504. st->codec->codec_tag = bytestream_get_le32(pp);
  1505. av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
  1506. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1507. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1508. break;
  1509. case 0x52: /* stream identifier descriptor */
  1510. st->stream_identifier = 1 + get8(pp, desc_end);
  1511. break;
  1512. case 0x26: /* metadata descriptor */
  1513. if (get16(pp, desc_end) == 0xFFFF)
  1514. *pp += 4;
  1515. if (get8(pp, desc_end) == 0xFF) {
  1516. st->codec->codec_tag = bytestream_get_le32(pp);
  1517. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1518. mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
  1519. }
  1520. break;
  1521. default:
  1522. break;
  1523. }
  1524. *pp = desc_end;
  1525. return 0;
  1526. }
  1527. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1528. {
  1529. MpegTSContext *ts = filter->u.section_filter.opaque;
  1530. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1531. SectionHeader h1, *h = &h1;
  1532. PESContext *pes;
  1533. AVStream *st;
  1534. const uint8_t *p, *p_end, *desc_list_end;
  1535. int program_info_length, pcr_pid, pid, stream_type;
  1536. int desc_list_len;
  1537. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1538. int mp4_descr_count = 0;
  1539. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1540. int i;
  1541. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1542. hex_dump_debug(ts->stream, section, section_len);
  1543. p_end = section + section_len - 4;
  1544. p = section;
  1545. if (parse_section_header(h, &p, p_end) < 0)
  1546. return;
  1547. if (h->version == tssf->last_ver)
  1548. return;
  1549. tssf->last_ver = h->version;
  1550. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1551. h->id, h->sec_num, h->last_sec_num);
  1552. if (h->tid != PMT_TID)
  1553. return;
  1554. if (ts->skip_changes)
  1555. return;
  1556. clear_program(ts, h->id);
  1557. pcr_pid = get16(&p, p_end);
  1558. if (pcr_pid < 0)
  1559. return;
  1560. pcr_pid &= 0x1fff;
  1561. add_pid_to_pmt(ts, h->id, pcr_pid);
  1562. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1563. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1564. program_info_length = get16(&p, p_end);
  1565. if (program_info_length < 0)
  1566. return;
  1567. program_info_length &= 0xfff;
  1568. while (program_info_length >= 2) {
  1569. uint8_t tag, len;
  1570. tag = get8(&p, p_end);
  1571. len = get8(&p, p_end);
  1572. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1573. if (len > program_info_length - 2)
  1574. // something else is broken, exit the program_descriptors_loop
  1575. break;
  1576. program_info_length -= len + 2;
  1577. if (tag == 0x1d) { // IOD descriptor
  1578. get8(&p, p_end); // scope
  1579. get8(&p, p_end); // label
  1580. len -= 2;
  1581. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1582. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1583. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1584. prog_reg_desc = bytestream_get_le32(&p);
  1585. len -= 4;
  1586. }
  1587. p += len;
  1588. }
  1589. p += program_info_length;
  1590. if (p >= p_end)
  1591. goto out;
  1592. // stop parsing after pmt, we found header
  1593. if (!ts->stream->nb_streams)
  1594. ts->stop_parse = 2;
  1595. set_pmt_found(ts, h->id);
  1596. for (;;) {
  1597. st = 0;
  1598. pes = NULL;
  1599. stream_type = get8(&p, p_end);
  1600. if (stream_type < 0)
  1601. break;
  1602. pid = get16(&p, p_end);
  1603. if (pid < 0)
  1604. goto out;
  1605. pid &= 0x1fff;
  1606. if (pid == ts->current_pid)
  1607. goto out;
  1608. /* now create stream */
  1609. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1610. pes = ts->pids[pid]->u.pes_filter.opaque;
  1611. if (!pes->st) {
  1612. pes->st = avformat_new_stream(pes->stream, NULL);
  1613. if (!pes->st)
  1614. goto out;
  1615. pes->st->id = pes->pid;
  1616. }
  1617. st = pes->st;
  1618. } else if (stream_type != 0x13) {
  1619. if (ts->pids[pid])
  1620. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1621. pes = add_pes_stream(ts, pid, pcr_pid);
  1622. if (pes) {
  1623. st = avformat_new_stream(pes->stream, NULL);
  1624. if (!st)
  1625. goto out;
  1626. st->id = pes->pid;
  1627. }
  1628. } else {
  1629. int idx = ff_find_stream_index(ts->stream, pid);
  1630. if (idx >= 0) {
  1631. st = ts->stream->streams[idx];
  1632. } else {
  1633. st = avformat_new_stream(ts->stream, NULL);
  1634. if (!st)
  1635. goto out;
  1636. st->id = pid;
  1637. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1638. }
  1639. }
  1640. if (!st)
  1641. goto out;
  1642. if (pes && !pes->stream_type)
  1643. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1644. add_pid_to_pmt(ts, h->id, pid);
  1645. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1646. desc_list_len = get16(&p, p_end);
  1647. if (desc_list_len < 0)
  1648. goto out;
  1649. desc_list_len &= 0xfff;
  1650. desc_list_end = p + desc_list_len;
  1651. if (desc_list_end > p_end)
  1652. goto out;
  1653. for (;;) {
  1654. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1655. desc_list_end, mp4_descr,
  1656. mp4_descr_count, pid, ts) < 0)
  1657. break;
  1658. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1659. stream_type == 0x83 && pes->sub_st) {
  1660. ff_program_add_stream_index(ts->stream, h->id,
  1661. pes->sub_st->index);
  1662. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1663. }
  1664. }
  1665. p = desc_list_end;
  1666. }
  1667. if (!ts->pids[pcr_pid])
  1668. mpegts_open_pcr_filter(ts, pcr_pid);
  1669. out:
  1670. for (i = 0; i < mp4_descr_count; i++)
  1671. av_free(mp4_descr[i].dec_config_descr);
  1672. }
  1673. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1674. {
  1675. MpegTSContext *ts = filter->u.section_filter.opaque;
  1676. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1677. SectionHeader h1, *h = &h1;
  1678. const uint8_t *p, *p_end;
  1679. int sid, pmt_pid;
  1680. AVProgram *program;
  1681. av_dlog(ts->stream, "PAT:\n");
  1682. hex_dump_debug(ts->stream, section, section_len);
  1683. p_end = section + section_len - 4;
  1684. p = section;
  1685. if (parse_section_header(h, &p, p_end) < 0)
  1686. return;
  1687. if (h->tid != PAT_TID)
  1688. return;
  1689. if (ts->skip_changes)
  1690. return;
  1691. if (h->version == tssf->last_ver)
  1692. return;
  1693. tssf->last_ver = h->version;
  1694. ts->stream->ts_id = h->id;
  1695. clear_programs(ts);
  1696. for (;;) {
  1697. sid = get16(&p, p_end);
  1698. if (sid < 0)
  1699. break;
  1700. pmt_pid = get16(&p, p_end);
  1701. if (pmt_pid < 0)
  1702. break;
  1703. pmt_pid &= 0x1fff;
  1704. if (pmt_pid == ts->current_pid)
  1705. break;
  1706. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1707. if (sid == 0x0000) {
  1708. /* NIT info */
  1709. } else {
  1710. MpegTSFilter *fil = ts->pids[pmt_pid];
  1711. program = av_new_program(ts->stream, sid);
  1712. program->program_num = sid;
  1713. program->pmt_pid = pmt_pid;
  1714. if (fil)
  1715. if ( fil->type != MPEGTS_SECTION
  1716. || fil->pid != pmt_pid
  1717. || fil->u.section_filter.section_cb != pmt_cb)
  1718. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1719. if (!ts->pids[pmt_pid])
  1720. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1721. add_pat_entry(ts, sid);
  1722. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1723. add_pid_to_pmt(ts, sid, pmt_pid);
  1724. }
  1725. }
  1726. if (sid < 0) {
  1727. int i,j;
  1728. for (j=0; j<ts->stream->nb_programs; j++) {
  1729. for (i = 0; i < ts->nb_prg; i++)
  1730. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1731. break;
  1732. if (i==ts->nb_prg && !ts->skip_clear)
  1733. clear_avprogram(ts, ts->stream->programs[j]->id);
  1734. }
  1735. }
  1736. }
  1737. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1738. {
  1739. MpegTSContext *ts = filter->u.section_filter.opaque;
  1740. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1741. SectionHeader h1, *h = &h1;
  1742. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1743. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1744. char *name, *provider_name;
  1745. av_dlog(ts->stream, "SDT:\n");
  1746. hex_dump_debug(ts->stream, section, section_len);
  1747. p_end = section + section_len - 4;
  1748. p = section;
  1749. if (parse_section_header(h, &p, p_end) < 0)
  1750. return;
  1751. if (h->tid != SDT_TID)
  1752. return;
  1753. if (ts->skip_changes)
  1754. return;
  1755. if (h->version == tssf->last_ver)
  1756. return;
  1757. tssf->last_ver = h->version;
  1758. onid = get16(&p, p_end);
  1759. if (onid < 0)
  1760. return;
  1761. val = get8(&p, p_end);
  1762. if (val < 0)
  1763. return;
  1764. for (;;) {
  1765. sid = get16(&p, p_end);
  1766. if (sid < 0)
  1767. break;
  1768. val = get8(&p, p_end);
  1769. if (val < 0)
  1770. break;
  1771. desc_list_len = get16(&p, p_end);
  1772. if (desc_list_len < 0)
  1773. break;
  1774. desc_list_len &= 0xfff;
  1775. desc_list_end = p + desc_list_len;
  1776. if (desc_list_end > p_end)
  1777. break;
  1778. for (;;) {
  1779. desc_tag = get8(&p, desc_list_end);
  1780. if (desc_tag < 0)
  1781. break;
  1782. desc_len = get8(&p, desc_list_end);
  1783. desc_end = p + desc_len;
  1784. if (desc_len < 0 || desc_end > desc_list_end)
  1785. break;
  1786. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1787. desc_tag, desc_len);
  1788. switch (desc_tag) {
  1789. case 0x48:
  1790. service_type = get8(&p, p_end);
  1791. if (service_type < 0)
  1792. break;
  1793. provider_name = getstr8(&p, p_end);
  1794. if (!provider_name)
  1795. break;
  1796. name = getstr8(&p, p_end);
  1797. if (name) {
  1798. AVProgram *program = av_new_program(ts->stream, sid);
  1799. if (program) {
  1800. av_dict_set(&program->metadata, "service_name", name, 0);
  1801. av_dict_set(&program->metadata, "service_provider",
  1802. provider_name, 0);
  1803. }
  1804. }
  1805. av_free(name);
  1806. av_free(provider_name);
  1807. break;
  1808. default:
  1809. break;
  1810. }
  1811. p = desc_end;
  1812. }
  1813. p = desc_list_end;
  1814. }
  1815. }
  1816. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1817. const uint8_t *packet);
  1818. /* handle one TS packet */
  1819. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1820. {
  1821. MpegTSFilter *tss;
  1822. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1823. has_adaptation, has_payload;
  1824. const uint8_t *p, *p_end;
  1825. int64_t pos;
  1826. pid = AV_RB16(packet + 1) & 0x1fff;
  1827. if (pid && discard_pid(ts, pid))
  1828. return 0;
  1829. is_start = packet[1] & 0x40;
  1830. tss = ts->pids[pid];
  1831. if (ts->auto_guess && !tss && is_start) {
  1832. add_pes_stream(ts, pid, -1);
  1833. tss = ts->pids[pid];
  1834. }
  1835. if (!tss)
  1836. return 0;
  1837. ts->current_pid = pid;
  1838. afc = (packet[3] >> 4) & 3;
  1839. if (afc == 0) /* reserved value */
  1840. return 0;
  1841. has_adaptation = afc & 2;
  1842. has_payload = afc & 1;
  1843. is_discontinuity = has_adaptation &&
  1844. packet[4] != 0 && /* with length > 0 */
  1845. (packet[5] & 0x80); /* and discontinuity indicated */
  1846. /* continuity check (currently not used) */
  1847. cc = (packet[3] & 0xf);
  1848. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1849. cc_ok = pid == 0x1FFF || // null packet PID
  1850. is_discontinuity ||
  1851. tss->last_cc < 0 ||
  1852. expected_cc == cc;
  1853. tss->last_cc = cc;
  1854. if (!cc_ok) {
  1855. av_log(ts->stream, AV_LOG_DEBUG,
  1856. "Continuity check failed for pid %d expected %d got %d\n",
  1857. pid, expected_cc, cc);
  1858. if (tss->type == MPEGTS_PES) {
  1859. PESContext *pc = tss->u.pes_filter.opaque;
  1860. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1861. }
  1862. }
  1863. p = packet + 4;
  1864. if (has_adaptation) {
  1865. int64_t pcr_h;
  1866. int pcr_l;
  1867. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1868. tss->last_pcr = pcr_h * 300 + pcr_l;
  1869. /* skip adaptation field */
  1870. p += p[0] + 1;
  1871. }
  1872. /* if past the end of packet, ignore */
  1873. p_end = packet + TS_PACKET_SIZE;
  1874. if (p >= p_end || !has_payload)
  1875. return 0;
  1876. pos = avio_tell(ts->stream->pb);
  1877. if (pos >= 0) {
  1878. av_assert0(pos >= TS_PACKET_SIZE);
  1879. ts->pos47_full = pos - TS_PACKET_SIZE;
  1880. }
  1881. if (tss->type == MPEGTS_SECTION) {
  1882. if (is_start) {
  1883. /* pointer field present */
  1884. len = *p++;
  1885. if (p + len > p_end)
  1886. return 0;
  1887. if (len && cc_ok) {
  1888. /* write remaining section bytes */
  1889. write_section_data(ts, tss,
  1890. p, len, 0);
  1891. /* check whether filter has been closed */
  1892. if (!ts->pids[pid])
  1893. return 0;
  1894. }
  1895. p += len;
  1896. if (p < p_end) {
  1897. write_section_data(ts, tss,
  1898. p, p_end - p, 1);
  1899. }
  1900. } else {
  1901. if (cc_ok) {
  1902. write_section_data(ts, tss,
  1903. p, p_end - p, 0);
  1904. }
  1905. }
  1906. // stop find_stream_info from waiting for more streams
  1907. // when all programs have received a PMT
  1908. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER) {
  1909. int i;
  1910. for (i = 0; i < ts->nb_prg; i++) {
  1911. if (!ts->prg[i].pmt_found)
  1912. break;
  1913. }
  1914. if (i == ts->nb_prg && ts->nb_prg > 0) {
  1915. if (ts->stream->nb_streams > 1 || pos > 100000) {
  1916. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  1917. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1918. }
  1919. }
  1920. }
  1921. } else {
  1922. int ret;
  1923. // Note: The position here points actually behind the current packet.
  1924. if (tss->type == MPEGTS_PES) {
  1925. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1926. pos - ts->raw_packet_size)) < 0)
  1927. return ret;
  1928. }
  1929. }
  1930. return 0;
  1931. }
  1932. static void reanalyze(MpegTSContext *ts) {
  1933. AVIOContext *pb = ts->stream->pb;
  1934. int64_t pos = avio_tell(pb);
  1935. if (pos < 0)
  1936. return;
  1937. pos -= ts->pos47_full;
  1938. if (pos == TS_PACKET_SIZE) {
  1939. ts->size_stat[0] ++;
  1940. } else if (pos == TS_DVHS_PACKET_SIZE) {
  1941. ts->size_stat[1] ++;
  1942. } else if (pos == TS_FEC_PACKET_SIZE) {
  1943. ts->size_stat[2] ++;
  1944. }
  1945. ts->size_stat_count ++;
  1946. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  1947. int newsize = 0;
  1948. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  1949. newsize = TS_PACKET_SIZE;
  1950. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  1951. newsize = TS_DVHS_PACKET_SIZE;
  1952. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  1953. newsize = TS_FEC_PACKET_SIZE;
  1954. }
  1955. if (newsize && newsize != ts->raw_packet_size) {
  1956. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  1957. ts->raw_packet_size = newsize;
  1958. }
  1959. ts->size_stat_count = 0;
  1960. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  1961. }
  1962. }
  1963. /* XXX: try to find a better synchro over several packets (use
  1964. * get_packet_size() ?) */
  1965. static int mpegts_resync(AVFormatContext *s)
  1966. {
  1967. MpegTSContext *ts = s->priv_data;
  1968. AVIOContext *pb = s->pb;
  1969. int c, i;
  1970. for (i = 0; i < ts->resync_size; i++) {
  1971. c = avio_r8(pb);
  1972. if (avio_feof(pb))
  1973. return AVERROR_EOF;
  1974. if (c == 0x47) {
  1975. avio_seek(pb, -1, SEEK_CUR);
  1976. reanalyze(s->priv_data);
  1977. return 0;
  1978. }
  1979. }
  1980. av_log(s, AV_LOG_ERROR,
  1981. "max resync size reached, could not find sync byte\n");
  1982. /* no sync found */
  1983. return AVERROR_INVALIDDATA;
  1984. }
  1985. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  1986. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  1987. const uint8_t **data)
  1988. {
  1989. AVIOContext *pb = s->pb;
  1990. int len;
  1991. for (;;) {
  1992. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  1993. if (len != TS_PACKET_SIZE)
  1994. return len < 0 ? len : AVERROR_EOF;
  1995. /* check packet sync byte */
  1996. if ((*data)[0] != 0x47) {
  1997. /* find a new packet start */
  1998. uint64_t pos = avio_tell(pb);
  1999. avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
  2000. if (mpegts_resync(s) < 0)
  2001. return AVERROR(EAGAIN);
  2002. else
  2003. continue;
  2004. } else {
  2005. break;
  2006. }
  2007. }
  2008. return 0;
  2009. }
  2010. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  2011. {
  2012. AVIOContext *pb = s->pb;
  2013. int skip = raw_packet_size - TS_PACKET_SIZE;
  2014. if (skip > 0)
  2015. avio_skip(pb, skip);
  2016. }
  2017. static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
  2018. {
  2019. AVFormatContext *s = ts->stream;
  2020. uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  2021. const uint8_t *data;
  2022. int64_t packet_num;
  2023. int ret = 0;
  2024. if (avio_tell(s->pb) != ts->last_pos) {
  2025. int i;
  2026. av_dlog(ts->stream, "Skipping after seek\n");
  2027. /* seek detected, flush pes buffer */
  2028. for (i = 0; i < NB_PID_MAX; i++) {
  2029. if (ts->pids[i]) {
  2030. if (ts->pids[i]->type == MPEGTS_PES) {
  2031. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2032. av_buffer_unref(&pes->buffer);
  2033. pes->data_index = 0;
  2034. pes->state = MPEGTS_SKIP; /* skip until pes header */
  2035. } else if (ts->pids[i]->type == MPEGTS_SECTION) {
  2036. ts->pids[i]->u.section_filter.last_ver = -1;
  2037. }
  2038. ts->pids[i]->last_cc = -1;
  2039. ts->pids[i]->last_pcr = -1;
  2040. }
  2041. }
  2042. }
  2043. ts->stop_parse = 0;
  2044. packet_num = 0;
  2045. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2046. for (;;) {
  2047. packet_num++;
  2048. if (nb_packets != 0 && packet_num >= nb_packets ||
  2049. ts->stop_parse > 1) {
  2050. ret = AVERROR(EAGAIN);
  2051. break;
  2052. }
  2053. if (ts->stop_parse > 0)
  2054. break;
  2055. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2056. if (ret != 0)
  2057. break;
  2058. ret = handle_packet(ts, data);
  2059. finished_reading_packet(s, ts->raw_packet_size);
  2060. if (ret != 0)
  2061. break;
  2062. }
  2063. ts->last_pos = avio_tell(s->pb);
  2064. return ret;
  2065. }
  2066. static int mpegts_probe(AVProbeData *p)
  2067. {
  2068. const int size = p->buf_size;
  2069. int maxscore = 0;
  2070. int sumscore = 0;
  2071. int i;
  2072. int check_count = size / TS_FEC_PACKET_SIZE;
  2073. #define CHECK_COUNT 10
  2074. #define CHECK_BLOCK 100
  2075. if (check_count < CHECK_COUNT)
  2076. return AVERROR_INVALIDDATA;
  2077. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2078. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2079. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
  2080. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  2081. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  2082. score = FFMAX3(score, dvhs_score, fec_score);
  2083. sumscore += score;
  2084. maxscore = FFMAX(maxscore, score);
  2085. }
  2086. sumscore = sumscore * CHECK_COUNT / check_count;
  2087. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2088. av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2089. if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2090. else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2091. else
  2092. return AVERROR_INVALIDDATA;
  2093. }
  2094. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2095. * (-1) if not available */
  2096. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2097. {
  2098. int afc, len, flags;
  2099. const uint8_t *p;
  2100. unsigned int v;
  2101. afc = (packet[3] >> 4) & 3;
  2102. if (afc <= 1)
  2103. return AVERROR_INVALIDDATA;
  2104. p = packet + 4;
  2105. len = p[0];
  2106. p++;
  2107. if (len == 0)
  2108. return AVERROR_INVALIDDATA;
  2109. flags = *p++;
  2110. len--;
  2111. if (!(flags & 0x10))
  2112. return AVERROR_INVALIDDATA;
  2113. if (len < 6)
  2114. return AVERROR_INVALIDDATA;
  2115. v = AV_RB32(p);
  2116. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2117. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2118. return 0;
  2119. }
  2120. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2121. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2122. * probe buffer usually is big enough. Only warn if the seek failed
  2123. * on files where the seek should work. */
  2124. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2125. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2126. }
  2127. static int mpegts_read_header(AVFormatContext *s)
  2128. {
  2129. MpegTSContext *ts = s->priv_data;
  2130. AVIOContext *pb = s->pb;
  2131. uint8_t buf[8 * 1024] = {0};
  2132. int len;
  2133. int64_t pos, probesize = s->probesize ? s->probesize : s->probesize2;
  2134. ffio_ensure_seekback(pb, probesize);
  2135. /* read the first 8192 bytes to get packet size */
  2136. pos = avio_tell(pb);
  2137. len = avio_read(pb, buf, sizeof(buf));
  2138. ts->raw_packet_size = get_packet_size(buf, len);
  2139. if (ts->raw_packet_size <= 0) {
  2140. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2141. ts->raw_packet_size = TS_PACKET_SIZE;
  2142. }
  2143. ts->stream = s;
  2144. ts->auto_guess = 0;
  2145. if (s->iformat == &ff_mpegts_demuxer) {
  2146. /* normal demux */
  2147. /* first do a scan to get all the services */
  2148. seek_back(s, pb, pos);
  2149. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2150. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2151. handle_packets(ts, probesize / ts->raw_packet_size);
  2152. /* if could not find service, enable auto_guess */
  2153. ts->auto_guess = 1;
  2154. av_dlog(ts->stream, "tuning done\n");
  2155. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2156. } else {
  2157. AVStream *st;
  2158. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2159. int64_t pcrs[2], pcr_h;
  2160. int packet_count[2];
  2161. uint8_t packet[TS_PACKET_SIZE];
  2162. const uint8_t *data;
  2163. /* only read packets */
  2164. st = avformat_new_stream(s, NULL);
  2165. if (!st)
  2166. return AVERROR(ENOMEM);
  2167. avpriv_set_pts_info(st, 60, 1, 27000000);
  2168. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2169. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  2170. /* we iterate until we find two PCRs to estimate the bitrate */
  2171. pcr_pid = -1;
  2172. nb_pcrs = 0;
  2173. nb_packets = 0;
  2174. for (;;) {
  2175. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2176. if (ret < 0)
  2177. return ret;
  2178. pid = AV_RB16(data + 1) & 0x1fff;
  2179. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2180. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2181. finished_reading_packet(s, ts->raw_packet_size);
  2182. pcr_pid = pid;
  2183. packet_count[nb_pcrs] = nb_packets;
  2184. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2185. nb_pcrs++;
  2186. if (nb_pcrs >= 2)
  2187. break;
  2188. } else {
  2189. finished_reading_packet(s, ts->raw_packet_size);
  2190. }
  2191. nb_packets++;
  2192. }
  2193. /* NOTE1: the bitrate is computed without the FEC */
  2194. /* NOTE2: it is only the bitrate of the start of the stream */
  2195. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2196. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2197. s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
  2198. st->codec->bit_rate = s->bit_rate;
  2199. st->start_time = ts->cur_pcr;
  2200. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  2201. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2202. }
  2203. seek_back(s, pb, pos);
  2204. return 0;
  2205. }
  2206. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2207. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2208. {
  2209. MpegTSContext *ts = s->priv_data;
  2210. int ret, i;
  2211. int64_t pcr_h, next_pcr_h, pos;
  2212. int pcr_l, next_pcr_l;
  2213. uint8_t pcr_buf[12];
  2214. const uint8_t *data;
  2215. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2216. return AVERROR(ENOMEM);
  2217. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2218. pkt->pos = avio_tell(s->pb);
  2219. if (ret < 0) {
  2220. av_free_packet(pkt);
  2221. return ret;
  2222. }
  2223. if (data != pkt->data)
  2224. memcpy(pkt->data, data, ts->raw_packet_size);
  2225. finished_reading_packet(s, ts->raw_packet_size);
  2226. if (ts->mpeg2ts_compute_pcr) {
  2227. /* compute exact PCR for each packet */
  2228. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2229. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2230. pos = avio_tell(s->pb);
  2231. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2232. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2233. avio_read(s->pb, pcr_buf, 12);
  2234. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2235. /* XXX: not precise enough */
  2236. ts->pcr_incr =
  2237. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2238. (i + 1);
  2239. break;
  2240. }
  2241. }
  2242. avio_seek(s->pb, pos, SEEK_SET);
  2243. /* no next PCR found: we use previous increment */
  2244. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2245. }
  2246. pkt->pts = ts->cur_pcr;
  2247. pkt->duration = ts->pcr_incr;
  2248. ts->cur_pcr += ts->pcr_incr;
  2249. }
  2250. pkt->stream_index = 0;
  2251. return 0;
  2252. }
  2253. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2254. {
  2255. MpegTSContext *ts = s->priv_data;
  2256. int ret, i;
  2257. pkt->size = -1;
  2258. ts->pkt = pkt;
  2259. ret = handle_packets(ts, 0);
  2260. if (ret < 0) {
  2261. av_free_packet(ts->pkt);
  2262. /* flush pes data left */
  2263. for (i = 0; i < NB_PID_MAX; i++)
  2264. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2265. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2266. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2267. new_pes_packet(pes, pkt);
  2268. pes->state = MPEGTS_SKIP;
  2269. ret = 0;
  2270. break;
  2271. }
  2272. }
  2273. }
  2274. if (!ret && pkt->size < 0)
  2275. ret = AVERROR(EINTR);
  2276. return ret;
  2277. }
  2278. static void mpegts_free(MpegTSContext *ts)
  2279. {
  2280. int i;
  2281. clear_programs(ts);
  2282. for (i = 0; i < NB_PID_MAX; i++)
  2283. if (ts->pids[i])
  2284. mpegts_close_filter(ts, ts->pids[i]);
  2285. }
  2286. static int mpegts_read_close(AVFormatContext *s)
  2287. {
  2288. MpegTSContext *ts = s->priv_data;
  2289. mpegts_free(ts);
  2290. return 0;
  2291. }
  2292. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2293. int64_t *ppos, int64_t pos_limit)
  2294. {
  2295. MpegTSContext *ts = s->priv_data;
  2296. int64_t pos, timestamp;
  2297. uint8_t buf[TS_PACKET_SIZE];
  2298. int pcr_l, pcr_pid =
  2299. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2300. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2301. pos =
  2302. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2303. ts->raw_packet_size + pos47;
  2304. while(pos < pos_limit) {
  2305. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2306. return AV_NOPTS_VALUE;
  2307. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2308. return AV_NOPTS_VALUE;
  2309. if (buf[0] != 0x47) {
  2310. avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
  2311. if (mpegts_resync(s) < 0)
  2312. return AV_NOPTS_VALUE;
  2313. pos = avio_tell(s->pb);
  2314. continue;
  2315. }
  2316. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2317. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2318. *ppos = pos;
  2319. return timestamp;
  2320. }
  2321. pos += ts->raw_packet_size;
  2322. }
  2323. return AV_NOPTS_VALUE;
  2324. }
  2325. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2326. int64_t *ppos, int64_t pos_limit)
  2327. {
  2328. MpegTSContext *ts = s->priv_data;
  2329. int64_t pos;
  2330. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2331. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2332. ff_read_frame_flush(s);
  2333. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2334. return AV_NOPTS_VALUE;
  2335. while(pos < pos_limit) {
  2336. int ret;
  2337. AVPacket pkt;
  2338. av_init_packet(&pkt);
  2339. ret = av_read_frame(s, &pkt);
  2340. if (ret < 0)
  2341. return AV_NOPTS_VALUE;
  2342. av_free_packet(&pkt);
  2343. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2344. ff_reduce_index(s, pkt.stream_index);
  2345. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2346. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2347. *ppos = pkt.pos;
  2348. return pkt.dts;
  2349. }
  2350. }
  2351. pos = pkt.pos;
  2352. }
  2353. return AV_NOPTS_VALUE;
  2354. }
  2355. /**************************************************************/
  2356. /* parsing functions - called from other demuxers such as RTP */
  2357. MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
  2358. {
  2359. MpegTSContext *ts;
  2360. ts = av_mallocz(sizeof(MpegTSContext));
  2361. if (!ts)
  2362. return NULL;
  2363. /* no stream case, currently used by RTP */
  2364. ts->raw_packet_size = TS_PACKET_SIZE;
  2365. ts->stream = s;
  2366. ts->auto_guess = 1;
  2367. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2368. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2369. return ts;
  2370. }
  2371. /* return the consumed length if a packet was output, or -1 if no
  2372. * packet is output */
  2373. int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2374. const uint8_t *buf, int len)
  2375. {
  2376. int len1;
  2377. len1 = len;
  2378. ts->pkt = pkt;
  2379. for (;;) {
  2380. ts->stop_parse = 0;
  2381. if (len < TS_PACKET_SIZE)
  2382. return AVERROR_INVALIDDATA;
  2383. if (buf[0] != 0x47) {
  2384. buf++;
  2385. len--;
  2386. } else {
  2387. handle_packet(ts, buf);
  2388. buf += TS_PACKET_SIZE;
  2389. len -= TS_PACKET_SIZE;
  2390. if (ts->stop_parse == 1)
  2391. break;
  2392. }
  2393. }
  2394. return len1 - len;
  2395. }
  2396. void avpriv_mpegts_parse_close(MpegTSContext *ts)
  2397. {
  2398. mpegts_free(ts);
  2399. av_free(ts);
  2400. }
  2401. AVInputFormat ff_mpegts_demuxer = {
  2402. .name = "mpegts",
  2403. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2404. .priv_data_size = sizeof(MpegTSContext),
  2405. .read_probe = mpegts_probe,
  2406. .read_header = mpegts_read_header,
  2407. .read_packet = mpegts_read_packet,
  2408. .read_close = mpegts_read_close,
  2409. .read_timestamp = mpegts_get_dts,
  2410. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2411. .priv_class = &mpegts_class,
  2412. };
  2413. AVInputFormat ff_mpegtsraw_demuxer = {
  2414. .name = "mpegtsraw",
  2415. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2416. .priv_data_size = sizeof(MpegTSContext),
  2417. .read_header = mpegts_read_header,
  2418. .read_packet = mpegts_raw_read_packet,
  2419. .read_close = mpegts_read_close,
  2420. .read_timestamp = mpegts_get_dts,
  2421. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2422. .priv_class = &mpegtsraw_class,
  2423. };