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.

2756 lines
90KB

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