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.

3037 lines
101KB

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