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.

3049 lines
102KB

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