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.

2853 lines
94KB

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