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.

3054 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 0x02: /* video stream descriptor */
  1486. if (get8(pp, desc_end) & 0x1) {
  1487. st->disposition |= AV_DISPOSITION_STILL_IMAGE;
  1488. }
  1489. break;
  1490. case 0x1E: /* SL descriptor */
  1491. desc_es_id = get16(pp, desc_end);
  1492. if (desc_es_id < 0)
  1493. break;
  1494. if (ts && ts->pids[pid])
  1495. ts->pids[pid]->es_id = desc_es_id;
  1496. for (i = 0; i < mp4_descr_count; i++)
  1497. if (mp4_descr[i].dec_config_descr_len &&
  1498. mp4_descr[i].es_id == desc_es_id) {
  1499. AVIOContext pb;
  1500. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1501. mp4_descr[i].dec_config_descr_len, 0,
  1502. NULL, NULL, NULL, NULL);
  1503. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1504. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  1505. st->codecpar->extradata_size > 0) {
  1506. st->need_parsing = 0;
  1507. st->internal->need_context_update = 1;
  1508. }
  1509. if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1510. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1511. }
  1512. break;
  1513. case 0x1F: /* FMC descriptor */
  1514. if (get16(pp, desc_end) < 0)
  1515. break;
  1516. if (mp4_descr_count > 0 &&
  1517. (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
  1518. (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
  1519. st->request_probe > 0) &&
  1520. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1521. AVIOContext pb;
  1522. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1523. mp4_descr->dec_config_descr_len, 0,
  1524. NULL, NULL, NULL, NULL);
  1525. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1526. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  1527. st->codecpar->extradata_size > 0) {
  1528. st->request_probe = st->need_parsing = 0;
  1529. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1530. st->internal->need_context_update = 1;
  1531. }
  1532. }
  1533. break;
  1534. case 0x56: /* DVB teletext descriptor */
  1535. {
  1536. uint8_t *extradata = NULL;
  1537. int language_count = desc_len / 5;
  1538. if (desc_len > 0 && desc_len % 5 != 0)
  1539. return AVERROR_INVALIDDATA;
  1540. if (language_count > 0) {
  1541. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1542. av_assert0(language_count <= sizeof(language) / 4);
  1543. if (st->codecpar->extradata == NULL) {
  1544. if (ff_alloc_extradata(st->codecpar, language_count * 2)) {
  1545. return AVERROR(ENOMEM);
  1546. }
  1547. }
  1548. if (st->codecpar->extradata_size < language_count * 2)
  1549. return AVERROR_INVALIDDATA;
  1550. extradata = st->codecpar->extradata;
  1551. for (i = 0; i < language_count; i++) {
  1552. language[i * 4 + 0] = get8(pp, desc_end);
  1553. language[i * 4 + 1] = get8(pp, desc_end);
  1554. language[i * 4 + 2] = get8(pp, desc_end);
  1555. language[i * 4 + 3] = ',';
  1556. memcpy(extradata, *pp, 2);
  1557. extradata += 2;
  1558. *pp += 2;
  1559. }
  1560. language[i * 4 - 1] = 0;
  1561. av_dict_set(&st->metadata, "language", language, 0);
  1562. st->internal->need_context_update = 1;
  1563. }
  1564. }
  1565. break;
  1566. case 0x59: /* subtitling descriptor */
  1567. {
  1568. /* 8 bytes per DVB subtitle substream data:
  1569. * ISO_639_language_code (3 bytes),
  1570. * subtitling_type (1 byte),
  1571. * composition_page_id (2 bytes),
  1572. * ancillary_page_id (2 bytes) */
  1573. int language_count = desc_len / 8;
  1574. if (desc_len > 0 && desc_len % 8 != 0)
  1575. return AVERROR_INVALIDDATA;
  1576. if (language_count > 1) {
  1577. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1578. }
  1579. if (language_count > 0) {
  1580. uint8_t *extradata;
  1581. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1582. av_assert0(language_count <= sizeof(language) / 4);
  1583. if (st->codecpar->extradata == NULL) {
  1584. if (ff_alloc_extradata(st->codecpar, language_count * 5)) {
  1585. return AVERROR(ENOMEM);
  1586. }
  1587. }
  1588. if (st->codecpar->extradata_size < language_count * 5)
  1589. return AVERROR_INVALIDDATA;
  1590. extradata = st->codecpar->extradata;
  1591. for (i = 0; i < language_count; i++) {
  1592. language[i * 4 + 0] = get8(pp, desc_end);
  1593. language[i * 4 + 1] = get8(pp, desc_end);
  1594. language[i * 4 + 2] = get8(pp, desc_end);
  1595. language[i * 4 + 3] = ',';
  1596. /* hearing impaired subtitles detection using subtitling_type */
  1597. switch (*pp[0]) {
  1598. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1599. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1600. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1601. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1602. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1603. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1604. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1605. break;
  1606. }
  1607. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1608. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1609. extradata += 5;
  1610. *pp += 4;
  1611. }
  1612. language[i * 4 - 1] = 0;
  1613. av_dict_set(&st->metadata, "language", language, 0);
  1614. st->internal->need_context_update = 1;
  1615. }
  1616. }
  1617. break;
  1618. case 0x0a: /* ISO 639 language descriptor */
  1619. for (i = 0; i + 4 <= desc_len; i += 4) {
  1620. language[i + 0] = get8(pp, desc_end);
  1621. language[i + 1] = get8(pp, desc_end);
  1622. language[i + 2] = get8(pp, desc_end);
  1623. language[i + 3] = ',';
  1624. switch (get8(pp, desc_end)) {
  1625. case 0x01:
  1626. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1627. break;
  1628. case 0x02:
  1629. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1630. break;
  1631. case 0x03:
  1632. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1633. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1634. break;
  1635. }
  1636. }
  1637. if (i && language[0]) {
  1638. language[i - 1] = 0;
  1639. /* don't overwrite language, as it may already have been set by
  1640. * another, more specific descriptor (e.g. supplementary audio) */
  1641. av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
  1642. }
  1643. break;
  1644. case 0x05: /* registration descriptor */
  1645. st->codecpar->codec_tag = bytestream_get_le32(pp);
  1646. av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
  1647. if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) {
  1648. mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
  1649. if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
  1650. st->request_probe = 50;
  1651. }
  1652. break;
  1653. case 0x52: /* stream identifier descriptor */
  1654. st->stream_identifier = 1 + get8(pp, desc_end);
  1655. break;
  1656. case 0x26: /* metadata descriptor */
  1657. if (get16(pp, desc_end) == 0xFFFF)
  1658. *pp += 4;
  1659. if (get8(pp, desc_end) == 0xFF) {
  1660. st->codecpar->codec_tag = bytestream_get_le32(pp);
  1661. if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
  1662. mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
  1663. }
  1664. break;
  1665. case 0x7f: /* DVB extension descriptor */
  1666. ext_desc_tag = get8(pp, desc_end);
  1667. if (ext_desc_tag < 0)
  1668. return AVERROR_INVALIDDATA;
  1669. if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
  1670. ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
  1671. if (!st->codecpar->extradata) {
  1672. st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
  1673. AV_INPUT_BUFFER_PADDING_SIZE);
  1674. if (!st->codecpar->extradata)
  1675. return AVERROR(ENOMEM);
  1676. st->codecpar->extradata_size = sizeof(opus_default_extradata);
  1677. memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
  1678. channel_config_code = get8(pp, desc_end);
  1679. if (channel_config_code < 0)
  1680. return AVERROR_INVALIDDATA;
  1681. if (channel_config_code <= 0x8) {
  1682. st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
  1683. st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
  1684. st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
  1685. st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
  1686. memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
  1687. } else {
  1688. avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
  1689. }
  1690. st->need_parsing = AVSTREAM_PARSE_FULL;
  1691. st->internal->need_context_update = 1;
  1692. }
  1693. }
  1694. if (ext_desc_tag == 0x06) { /* supplementary audio descriptor */
  1695. int flags;
  1696. if (desc_len < 1)
  1697. return AVERROR_INVALIDDATA;
  1698. flags = get8(pp, desc_end);
  1699. if ((flags & 0x80) == 0) /* mix_type */
  1700. st->disposition |= AV_DISPOSITION_DEPENDENT;
  1701. switch ((flags >> 2) & 0x1F) { /* editorial_classification */
  1702. case 0x01:
  1703. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1704. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1705. break;
  1706. case 0x02:
  1707. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1708. break;
  1709. case 0x03:
  1710. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1711. break;
  1712. }
  1713. if (flags & 0x01) { /* language_code_present */
  1714. if (desc_len < 4)
  1715. return AVERROR_INVALIDDATA;
  1716. language[0] = get8(pp, desc_end);
  1717. language[1] = get8(pp, desc_end);
  1718. language[2] = get8(pp, desc_end);
  1719. language[3] = 0;
  1720. /* This language always has to override a possible
  1721. * ISO 639 language descriptor language */
  1722. if (language[0])
  1723. av_dict_set(&st->metadata, "language", language, 0);
  1724. }
  1725. }
  1726. break;
  1727. case 0x6a: /* ac-3_descriptor */
  1728. {
  1729. int component_type_flag = get8(pp, desc_end) & (1 << 7);
  1730. if (component_type_flag) {
  1731. int component_type = get8(pp, desc_end);
  1732. int service_type_mask = 0x38; // 0b00111000
  1733. int service_type = ((component_type & service_type_mask) >> 3);
  1734. if (service_type == 0x02 /* 0b010 */) {
  1735. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1736. av_log(ts->stream, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
  1737. }
  1738. }
  1739. }
  1740. break;
  1741. case 0x7a: /* enhanced_ac-3_descriptor */
  1742. {
  1743. int component_type_flag = get8(pp, desc_end) & (1 << 7);
  1744. if (component_type_flag) {
  1745. int component_type = get8(pp, desc_end);
  1746. int service_type_mask = 0x38; // 0b00111000
  1747. int service_type = ((component_type & service_type_mask) >> 3);
  1748. if (service_type == 0x02 /* 0b010 */) {
  1749. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1750. av_log(ts->stream, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
  1751. }
  1752. }
  1753. }
  1754. break;
  1755. default:
  1756. break;
  1757. }
  1758. *pp = desc_end;
  1759. return 0;
  1760. }
  1761. static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
  1762. {
  1763. return !(stream_type == 0x13 ||
  1764. (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
  1765. }
  1766. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1767. {
  1768. MpegTSContext *ts = filter->u.section_filter.opaque;
  1769. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1770. SectionHeader h1, *h = &h1;
  1771. PESContext *pes;
  1772. AVStream *st;
  1773. const uint8_t *p, *p_end, *desc_list_end;
  1774. int program_info_length, pcr_pid, pid, stream_type;
  1775. int desc_list_len;
  1776. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1777. int mp4_descr_count = 0;
  1778. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1779. int i;
  1780. av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
  1781. hex_dump_debug(ts->stream, section, section_len);
  1782. p_end = section + section_len - 4;
  1783. p = section;
  1784. if (parse_section_header(h, &p, p_end) < 0)
  1785. return;
  1786. if (h->tid != PMT_TID)
  1787. return;
  1788. if (skip_identical(h, tssf))
  1789. return;
  1790. av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
  1791. h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
  1792. if (!ts->scan_all_pmts && ts->skip_changes)
  1793. return;
  1794. if (!ts->skip_clear)
  1795. clear_program(ts, h->id);
  1796. pcr_pid = get16(&p, p_end);
  1797. if (pcr_pid < 0)
  1798. return;
  1799. pcr_pid &= 0x1fff;
  1800. add_pid_to_pmt(ts, h->id, pcr_pid);
  1801. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1802. av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
  1803. program_info_length = get16(&p, p_end);
  1804. if (program_info_length < 0)
  1805. return;
  1806. program_info_length &= 0xfff;
  1807. while (program_info_length >= 2) {
  1808. uint8_t tag, len;
  1809. tag = get8(&p, p_end);
  1810. len = get8(&p, p_end);
  1811. av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
  1812. if (len > program_info_length - 2)
  1813. // something else is broken, exit the program_descriptors_loop
  1814. break;
  1815. program_info_length -= len + 2;
  1816. if (tag == 0x1d) { // IOD descriptor
  1817. get8(&p, p_end); // scope
  1818. get8(&p, p_end); // label
  1819. len -= 2;
  1820. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1821. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1822. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1823. prog_reg_desc = bytestream_get_le32(&p);
  1824. len -= 4;
  1825. }
  1826. p += len;
  1827. }
  1828. p += program_info_length;
  1829. if (p >= p_end)
  1830. goto out;
  1831. // stop parsing after pmt, we found header
  1832. if (!ts->stream->nb_streams)
  1833. ts->stop_parse = 2;
  1834. set_pmt_found(ts, h->id);
  1835. for (;;) {
  1836. st = 0;
  1837. pes = NULL;
  1838. stream_type = get8(&p, p_end);
  1839. if (stream_type < 0)
  1840. break;
  1841. pid = get16(&p, p_end);
  1842. if (pid < 0)
  1843. goto out;
  1844. pid &= 0x1fff;
  1845. if (pid == ts->current_pid)
  1846. goto out;
  1847. /* now create stream */
  1848. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1849. pes = ts->pids[pid]->u.pes_filter.opaque;
  1850. if (!pes->st) {
  1851. pes->st = avformat_new_stream(pes->stream, NULL);
  1852. if (!pes->st)
  1853. goto out;
  1854. pes->st->id = pes->pid;
  1855. }
  1856. st = pes->st;
  1857. } else if (is_pes_stream(stream_type, prog_reg_desc)) {
  1858. if (ts->pids[pid])
  1859. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1860. pes = add_pes_stream(ts, pid, pcr_pid);
  1861. if (pes) {
  1862. st = avformat_new_stream(pes->stream, NULL);
  1863. if (!st)
  1864. goto out;
  1865. st->id = pes->pid;
  1866. }
  1867. } else {
  1868. int idx = ff_find_stream_index(ts->stream, pid);
  1869. if (idx >= 0) {
  1870. st = ts->stream->streams[idx];
  1871. } else {
  1872. st = avformat_new_stream(ts->stream, NULL);
  1873. if (!st)
  1874. goto out;
  1875. st->id = pid;
  1876. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  1877. if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
  1878. mpegts_find_stream_type(st, stream_type, SCTE_types);
  1879. mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
  1880. }
  1881. }
  1882. }
  1883. if (!st)
  1884. goto out;
  1885. if (pes && !pes->stream_type)
  1886. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1887. add_pid_to_pmt(ts, h->id, pid);
  1888. av_program_add_stream_index(ts->stream, h->id, st->index);
  1889. desc_list_len = get16(&p, p_end);
  1890. if (desc_list_len < 0)
  1891. goto out;
  1892. desc_list_len &= 0xfff;
  1893. desc_list_end = p + desc_list_len;
  1894. if (desc_list_end > p_end)
  1895. goto out;
  1896. for (;;) {
  1897. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1898. desc_list_end, mp4_descr,
  1899. mp4_descr_count, pid, ts) < 0)
  1900. break;
  1901. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1902. stream_type == 0x83 && pes->sub_st) {
  1903. av_program_add_stream_index(ts->stream, h->id,
  1904. pes->sub_st->index);
  1905. pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
  1906. }
  1907. }
  1908. p = desc_list_end;
  1909. }
  1910. if (!ts->pids[pcr_pid])
  1911. mpegts_open_pcr_filter(ts, pcr_pid);
  1912. out:
  1913. for (i = 0; i < mp4_descr_count; i++)
  1914. av_free(mp4_descr[i].dec_config_descr);
  1915. }
  1916. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1917. {
  1918. MpegTSContext *ts = filter->u.section_filter.opaque;
  1919. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1920. SectionHeader h1, *h = &h1;
  1921. const uint8_t *p, *p_end;
  1922. int sid, pmt_pid;
  1923. AVProgram *program;
  1924. av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
  1925. hex_dump_debug(ts->stream, section, section_len);
  1926. p_end = section + section_len - 4;
  1927. p = section;
  1928. if (parse_section_header(h, &p, p_end) < 0)
  1929. return;
  1930. if (h->tid != PAT_TID)
  1931. return;
  1932. if (ts->skip_changes)
  1933. return;
  1934. if (skip_identical(h, tssf))
  1935. return;
  1936. ts->stream->ts_id = h->id;
  1937. clear_programs(ts);
  1938. for (;;) {
  1939. sid = get16(&p, p_end);
  1940. if (sid < 0)
  1941. break;
  1942. pmt_pid = get16(&p, p_end);
  1943. if (pmt_pid < 0)
  1944. break;
  1945. pmt_pid &= 0x1fff;
  1946. if (pmt_pid == ts->current_pid)
  1947. break;
  1948. av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1949. if (sid == 0x0000) {
  1950. /* NIT info */
  1951. } else {
  1952. MpegTSFilter *fil = ts->pids[pmt_pid];
  1953. program = av_new_program(ts->stream, sid);
  1954. if (program) {
  1955. program->program_num = sid;
  1956. program->pmt_pid = pmt_pid;
  1957. }
  1958. if (fil)
  1959. if ( fil->type != MPEGTS_SECTION
  1960. || fil->pid != pmt_pid
  1961. || fil->u.section_filter.section_cb != pmt_cb)
  1962. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1963. if (!ts->pids[pmt_pid])
  1964. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1965. add_pat_entry(ts, sid);
  1966. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1967. add_pid_to_pmt(ts, sid, pmt_pid);
  1968. }
  1969. }
  1970. if (sid < 0) {
  1971. int i,j;
  1972. for (j=0; j<ts->stream->nb_programs; j++) {
  1973. for (i = 0; i < ts->nb_prg; i++)
  1974. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1975. break;
  1976. if (i==ts->nb_prg && !ts->skip_clear)
  1977. clear_avprogram(ts, ts->stream->programs[j]->id);
  1978. }
  1979. }
  1980. }
  1981. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1982. {
  1983. MpegTSContext *ts = filter->u.section_filter.opaque;
  1984. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1985. SectionHeader h1, *h = &h1;
  1986. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1987. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1988. char *name, *provider_name;
  1989. av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
  1990. hex_dump_debug(ts->stream, section, section_len);
  1991. p_end = section + section_len - 4;
  1992. p = section;
  1993. if (parse_section_header(h, &p, p_end) < 0)
  1994. return;
  1995. if (h->tid != SDT_TID)
  1996. return;
  1997. if (ts->skip_changes)
  1998. return;
  1999. if (skip_identical(h, tssf))
  2000. return;
  2001. onid = get16(&p, p_end);
  2002. if (onid < 0)
  2003. return;
  2004. val = get8(&p, p_end);
  2005. if (val < 0)
  2006. return;
  2007. for (;;) {
  2008. sid = get16(&p, p_end);
  2009. if (sid < 0)
  2010. break;
  2011. val = get8(&p, p_end);
  2012. if (val < 0)
  2013. break;
  2014. desc_list_len = get16(&p, p_end);
  2015. if (desc_list_len < 0)
  2016. break;
  2017. desc_list_len &= 0xfff;
  2018. desc_list_end = p + desc_list_len;
  2019. if (desc_list_end > p_end)
  2020. break;
  2021. for (;;) {
  2022. desc_tag = get8(&p, desc_list_end);
  2023. if (desc_tag < 0)
  2024. break;
  2025. desc_len = get8(&p, desc_list_end);
  2026. desc_end = p + desc_len;
  2027. if (desc_len < 0 || desc_end > desc_list_end)
  2028. break;
  2029. av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
  2030. desc_tag, desc_len);
  2031. switch (desc_tag) {
  2032. case 0x48:
  2033. service_type = get8(&p, p_end);
  2034. if (service_type < 0)
  2035. break;
  2036. provider_name = getstr8(&p, p_end);
  2037. if (!provider_name)
  2038. break;
  2039. name = getstr8(&p, p_end);
  2040. if (name) {
  2041. AVProgram *program = av_new_program(ts->stream, sid);
  2042. if (program) {
  2043. av_dict_set(&program->metadata, "service_name", name, 0);
  2044. av_dict_set(&program->metadata, "service_provider",
  2045. provider_name, 0);
  2046. }
  2047. }
  2048. av_free(name);
  2049. av_free(provider_name);
  2050. break;
  2051. default:
  2052. break;
  2053. }
  2054. p = desc_end;
  2055. }
  2056. p = desc_list_end;
  2057. }
  2058. }
  2059. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  2060. const uint8_t *packet);
  2061. /* handle one TS packet */
  2062. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  2063. {
  2064. MpegTSFilter *tss;
  2065. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  2066. has_adaptation, has_payload;
  2067. const uint8_t *p, *p_end;
  2068. int64_t pos;
  2069. pid = AV_RB16(packet + 1) & 0x1fff;
  2070. if (pid && discard_pid(ts, pid))
  2071. return 0;
  2072. is_start = packet[1] & 0x40;
  2073. tss = ts->pids[pid];
  2074. if (ts->auto_guess && !tss && is_start) {
  2075. add_pes_stream(ts, pid, -1);
  2076. tss = ts->pids[pid];
  2077. }
  2078. if (!tss)
  2079. return 0;
  2080. ts->current_pid = pid;
  2081. afc = (packet[3] >> 4) & 3;
  2082. if (afc == 0) /* reserved value */
  2083. return 0;
  2084. has_adaptation = afc & 2;
  2085. has_payload = afc & 1;
  2086. is_discontinuity = has_adaptation &&
  2087. packet[4] != 0 && /* with length > 0 */
  2088. (packet[5] & 0x80); /* and discontinuity indicated */
  2089. /* continuity check (currently not used) */
  2090. cc = (packet[3] & 0xf);
  2091. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  2092. cc_ok = pid == 0x1FFF || // null packet PID
  2093. is_discontinuity ||
  2094. tss->last_cc < 0 ||
  2095. expected_cc == cc;
  2096. tss->last_cc = cc;
  2097. if (!cc_ok) {
  2098. av_log(ts->stream, AV_LOG_DEBUG,
  2099. "Continuity check failed for pid %d expected %d got %d\n",
  2100. pid, expected_cc, cc);
  2101. if (tss->type == MPEGTS_PES) {
  2102. PESContext *pc = tss->u.pes_filter.opaque;
  2103. pc->flags |= AV_PKT_FLAG_CORRUPT;
  2104. }
  2105. }
  2106. if (packet[1] & 0x80) {
  2107. av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
  2108. if (tss->type == MPEGTS_PES) {
  2109. PESContext *pc = tss->u.pes_filter.opaque;
  2110. pc->flags |= AV_PKT_FLAG_CORRUPT;
  2111. }
  2112. }
  2113. p = packet + 4;
  2114. if (has_adaptation) {
  2115. int64_t pcr_h;
  2116. int pcr_l;
  2117. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  2118. tss->last_pcr = pcr_h * 300 + pcr_l;
  2119. /* skip adaptation field */
  2120. p += p[0] + 1;
  2121. }
  2122. /* if past the end of packet, ignore */
  2123. p_end = packet + TS_PACKET_SIZE;
  2124. if (p >= p_end || !has_payload)
  2125. return 0;
  2126. pos = avio_tell(ts->stream->pb);
  2127. if (pos >= 0) {
  2128. av_assert0(pos >= TS_PACKET_SIZE);
  2129. ts->pos47_full = pos - TS_PACKET_SIZE;
  2130. }
  2131. if (tss->type == MPEGTS_SECTION) {
  2132. if (is_start) {
  2133. /* pointer field present */
  2134. len = *p++;
  2135. if (len > p_end - p)
  2136. return 0;
  2137. if (len && cc_ok) {
  2138. /* write remaining section bytes */
  2139. write_section_data(ts, tss,
  2140. p, len, 0);
  2141. /* check whether filter has been closed */
  2142. if (!ts->pids[pid])
  2143. return 0;
  2144. }
  2145. p += len;
  2146. if (p < p_end) {
  2147. write_section_data(ts, tss,
  2148. p, p_end - p, 1);
  2149. }
  2150. } else {
  2151. if (cc_ok) {
  2152. write_section_data(ts, tss,
  2153. p, p_end - p, 0);
  2154. }
  2155. }
  2156. // stop find_stream_info from waiting for more streams
  2157. // when all programs have received a PMT
  2158. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
  2159. int i;
  2160. for (i = 0; i < ts->nb_prg; i++) {
  2161. if (!ts->prg[i].pmt_found)
  2162. break;
  2163. }
  2164. if (i == ts->nb_prg && ts->nb_prg > 0) {
  2165. int types = 0;
  2166. for (i = 0; i < ts->stream->nb_streams; i++) {
  2167. AVStream *st = ts->stream->streams[i];
  2168. if (st->codecpar->codec_type >= 0)
  2169. types |= 1<<st->codecpar->codec_type;
  2170. }
  2171. if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
  2172. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  2173. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  2174. }
  2175. }
  2176. }
  2177. } else {
  2178. int ret;
  2179. // Note: The position here points actually behind the current packet.
  2180. if (tss->type == MPEGTS_PES) {
  2181. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  2182. pos - ts->raw_packet_size)) < 0)
  2183. return ret;
  2184. }
  2185. }
  2186. return 0;
  2187. }
  2188. static void reanalyze(MpegTSContext *ts) {
  2189. AVIOContext *pb = ts->stream->pb;
  2190. int64_t pos = avio_tell(pb);
  2191. if (pos < 0)
  2192. return;
  2193. pos -= ts->pos47_full;
  2194. if (pos == TS_PACKET_SIZE) {
  2195. ts->size_stat[0] ++;
  2196. } else if (pos == TS_DVHS_PACKET_SIZE) {
  2197. ts->size_stat[1] ++;
  2198. } else if (pos == TS_FEC_PACKET_SIZE) {
  2199. ts->size_stat[2] ++;
  2200. }
  2201. ts->size_stat_count ++;
  2202. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  2203. int newsize = 0;
  2204. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  2205. newsize = TS_PACKET_SIZE;
  2206. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  2207. newsize = TS_DVHS_PACKET_SIZE;
  2208. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  2209. newsize = TS_FEC_PACKET_SIZE;
  2210. }
  2211. if (newsize && newsize != ts->raw_packet_size) {
  2212. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  2213. ts->raw_packet_size = newsize;
  2214. }
  2215. ts->size_stat_count = 0;
  2216. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  2217. }
  2218. }
  2219. /* XXX: try to find a better synchro over several packets (use
  2220. * get_packet_size() ?) */
  2221. static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
  2222. {
  2223. MpegTSContext *ts = s->priv_data;
  2224. AVIOContext *pb = s->pb;
  2225. int c, i;
  2226. uint64_t pos = avio_tell(pb);
  2227. avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
  2228. //Special case for files like 01c56b0dc1.ts
  2229. if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
  2230. avio_seek(pb, 12, SEEK_CUR);
  2231. return 0;
  2232. }
  2233. for (i = 0; i < ts->resync_size; i++) {
  2234. c = avio_r8(pb);
  2235. if (avio_feof(pb))
  2236. return AVERROR_EOF;
  2237. if (c == 0x47) {
  2238. avio_seek(pb, -1, SEEK_CUR);
  2239. reanalyze(s->priv_data);
  2240. return 0;
  2241. }
  2242. }
  2243. av_log(s, AV_LOG_ERROR,
  2244. "max resync size reached, could not find sync byte\n");
  2245. /* no sync found */
  2246. return AVERROR_INVALIDDATA;
  2247. }
  2248. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  2249. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  2250. const uint8_t **data)
  2251. {
  2252. AVIOContext *pb = s->pb;
  2253. int len;
  2254. for (;;) {
  2255. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  2256. if (len != TS_PACKET_SIZE)
  2257. return len < 0 ? len : AVERROR_EOF;
  2258. /* check packet sync byte */
  2259. if ((*data)[0] != 0x47) {
  2260. /* find a new packet start */
  2261. if (mpegts_resync(s, raw_packet_size, *data) < 0)
  2262. return AVERROR(EAGAIN);
  2263. else
  2264. continue;
  2265. } else {
  2266. break;
  2267. }
  2268. }
  2269. return 0;
  2270. }
  2271. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  2272. {
  2273. AVIOContext *pb = s->pb;
  2274. int skip = raw_packet_size - TS_PACKET_SIZE;
  2275. if (skip > 0)
  2276. avio_skip(pb, skip);
  2277. }
  2278. static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
  2279. {
  2280. AVFormatContext *s = ts->stream;
  2281. uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
  2282. const uint8_t *data;
  2283. int64_t packet_num;
  2284. int ret = 0;
  2285. if (avio_tell(s->pb) != ts->last_pos) {
  2286. int i;
  2287. av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
  2288. /* seek detected, flush pes buffer */
  2289. for (i = 0; i < NB_PID_MAX; i++) {
  2290. if (ts->pids[i]) {
  2291. if (ts->pids[i]->type == MPEGTS_PES) {
  2292. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2293. av_buffer_unref(&pes->buffer);
  2294. pes->data_index = 0;
  2295. pes->state = MPEGTS_SKIP; /* skip until pes header */
  2296. } else if (ts->pids[i]->type == MPEGTS_SECTION) {
  2297. ts->pids[i]->u.section_filter.last_ver = -1;
  2298. }
  2299. ts->pids[i]->last_cc = -1;
  2300. ts->pids[i]->last_pcr = -1;
  2301. }
  2302. }
  2303. }
  2304. ts->stop_parse = 0;
  2305. packet_num = 0;
  2306. memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  2307. for (;;) {
  2308. packet_num++;
  2309. if (nb_packets != 0 && packet_num >= nb_packets ||
  2310. ts->stop_parse > 1) {
  2311. ret = AVERROR(EAGAIN);
  2312. break;
  2313. }
  2314. if (ts->stop_parse > 0)
  2315. break;
  2316. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2317. if (ret != 0)
  2318. break;
  2319. ret = handle_packet(ts, data);
  2320. finished_reading_packet(s, ts->raw_packet_size);
  2321. if (ret != 0)
  2322. break;
  2323. }
  2324. ts->last_pos = avio_tell(s->pb);
  2325. return ret;
  2326. }
  2327. static int mpegts_probe(AVProbeData *p)
  2328. {
  2329. const int size = p->buf_size;
  2330. int maxscore = 0;
  2331. int sumscore = 0;
  2332. int i;
  2333. int check_count = size / TS_FEC_PACKET_SIZE;
  2334. #define CHECK_COUNT 10
  2335. #define CHECK_BLOCK 100
  2336. if (!check_count)
  2337. return 0;
  2338. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2339. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2340. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
  2341. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
  2342. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
  2343. score = FFMAX3(score, dvhs_score, fec_score);
  2344. sumscore += score;
  2345. maxscore = FFMAX(maxscore, score);
  2346. }
  2347. sumscore = sumscore * CHECK_COUNT / check_count;
  2348. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2349. ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2350. if (check_count > CHECK_COUNT && sumscore > 6) {
  2351. return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2352. } else if (check_count >= CHECK_COUNT && sumscore > 6) {
  2353. return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2354. } else if (check_count >= CHECK_COUNT && maxscore > 6) {
  2355. return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2356. } else if (sumscore > 6) {
  2357. return 2;
  2358. } else {
  2359. return 0;
  2360. }
  2361. }
  2362. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2363. * (-1) if not available */
  2364. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2365. {
  2366. int afc, len, flags;
  2367. const uint8_t *p;
  2368. unsigned int v;
  2369. afc = (packet[3] >> 4) & 3;
  2370. if (afc <= 1)
  2371. return AVERROR_INVALIDDATA;
  2372. p = packet + 4;
  2373. len = p[0];
  2374. p++;
  2375. if (len == 0)
  2376. return AVERROR_INVALIDDATA;
  2377. flags = *p++;
  2378. len--;
  2379. if (!(flags & 0x10))
  2380. return AVERROR_INVALIDDATA;
  2381. if (len < 6)
  2382. return AVERROR_INVALIDDATA;
  2383. v = AV_RB32(p);
  2384. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2385. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2386. return 0;
  2387. }
  2388. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2389. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2390. * probe buffer usually is big enough. Only warn if the seek failed
  2391. * on files where the seek should work. */
  2392. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2393. av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2394. }
  2395. static int mpegts_read_header(AVFormatContext *s)
  2396. {
  2397. MpegTSContext *ts = s->priv_data;
  2398. AVIOContext *pb = s->pb;
  2399. uint8_t buf[8 * 1024] = {0};
  2400. int len;
  2401. int64_t pos, probesize = s->probesize;
  2402. s->internal->prefer_codec_framerate = 1;
  2403. if (ffio_ensure_seekback(pb, probesize) < 0)
  2404. av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
  2405. /* read the first 8192 bytes to get packet size */
  2406. pos = avio_tell(pb);
  2407. len = avio_read(pb, buf, sizeof(buf));
  2408. ts->raw_packet_size = get_packet_size(buf, len);
  2409. if (ts->raw_packet_size <= 0) {
  2410. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2411. ts->raw_packet_size = TS_PACKET_SIZE;
  2412. }
  2413. ts->stream = s;
  2414. ts->auto_guess = 0;
  2415. if (s->iformat == &ff_mpegts_demuxer) {
  2416. /* normal demux */
  2417. /* first do a scan to get all the services */
  2418. seek_back(s, pb, pos);
  2419. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2420. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2421. handle_packets(ts, probesize / ts->raw_packet_size);
  2422. /* if could not find service, enable auto_guess */
  2423. ts->auto_guess = 1;
  2424. av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
  2425. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2426. } else {
  2427. AVStream *st;
  2428. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2429. int64_t pcrs[2], pcr_h;
  2430. int packet_count[2];
  2431. uint8_t packet[TS_PACKET_SIZE];
  2432. const uint8_t *data;
  2433. /* only read packets */
  2434. st = avformat_new_stream(s, NULL);
  2435. if (!st)
  2436. return AVERROR(ENOMEM);
  2437. avpriv_set_pts_info(st, 60, 1, 27000000);
  2438. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2439. st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
  2440. /* we iterate until we find two PCRs to estimate the bitrate */
  2441. pcr_pid = -1;
  2442. nb_pcrs = 0;
  2443. nb_packets = 0;
  2444. for (;;) {
  2445. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2446. if (ret < 0)
  2447. return ret;
  2448. pid = AV_RB16(data + 1) & 0x1fff;
  2449. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2450. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2451. finished_reading_packet(s, ts->raw_packet_size);
  2452. pcr_pid = pid;
  2453. packet_count[nb_pcrs] = nb_packets;
  2454. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2455. nb_pcrs++;
  2456. if (nb_pcrs >= 2) {
  2457. if (pcrs[1] - pcrs[0] > 0) {
  2458. /* the difference needs to be positive to make sense for bitrate computation */
  2459. break;
  2460. } else {
  2461. av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
  2462. pcrs[0] = pcrs[1];
  2463. packet_count[0] = packet_count[1];
  2464. nb_pcrs--;
  2465. }
  2466. }
  2467. } else {
  2468. finished_reading_packet(s, ts->raw_packet_size);
  2469. }
  2470. nb_packets++;
  2471. }
  2472. /* NOTE1: the bitrate is computed without the FEC */
  2473. /* NOTE2: it is only the bitrate of the start of the stream */
  2474. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2475. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2476. s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
  2477. st->codecpar->bit_rate = s->bit_rate;
  2478. st->start_time = ts->cur_pcr;
  2479. av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
  2480. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2481. }
  2482. seek_back(s, pb, pos);
  2483. return 0;
  2484. }
  2485. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2486. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2487. {
  2488. MpegTSContext *ts = s->priv_data;
  2489. int ret, i;
  2490. int64_t pcr_h, next_pcr_h, pos;
  2491. int pcr_l, next_pcr_l;
  2492. uint8_t pcr_buf[12];
  2493. const uint8_t *data;
  2494. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2495. return AVERROR(ENOMEM);
  2496. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2497. pkt->pos = avio_tell(s->pb);
  2498. if (ret < 0) {
  2499. av_packet_unref(pkt);
  2500. return ret;
  2501. }
  2502. if (data != pkt->data)
  2503. memcpy(pkt->data, data, ts->raw_packet_size);
  2504. finished_reading_packet(s, ts->raw_packet_size);
  2505. if (ts->mpeg2ts_compute_pcr) {
  2506. /* compute exact PCR for each packet */
  2507. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2508. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2509. pos = avio_tell(s->pb);
  2510. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2511. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2512. avio_read(s->pb, pcr_buf, 12);
  2513. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2514. /* XXX: not precise enough */
  2515. ts->pcr_incr =
  2516. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2517. (i + 1);
  2518. break;
  2519. }
  2520. }
  2521. avio_seek(s->pb, pos, SEEK_SET);
  2522. /* no next PCR found: we use previous increment */
  2523. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2524. }
  2525. pkt->pts = ts->cur_pcr;
  2526. pkt->duration = ts->pcr_incr;
  2527. ts->cur_pcr += ts->pcr_incr;
  2528. }
  2529. pkt->stream_index = 0;
  2530. return 0;
  2531. }
  2532. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2533. {
  2534. MpegTSContext *ts = s->priv_data;
  2535. int ret, i;
  2536. pkt->size = -1;
  2537. ts->pkt = pkt;
  2538. ret = handle_packets(ts, 0);
  2539. if (ret < 0) {
  2540. av_packet_unref(ts->pkt);
  2541. /* flush pes data left */
  2542. for (i = 0; i < NB_PID_MAX; i++)
  2543. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2544. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2545. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2546. ret = new_pes_packet(pes, pkt);
  2547. if (ret < 0)
  2548. return ret;
  2549. pes->state = MPEGTS_SKIP;
  2550. ret = 0;
  2551. break;
  2552. }
  2553. }
  2554. }
  2555. if (!ret && pkt->size < 0)
  2556. ret = AVERROR_INVALIDDATA;
  2557. return ret;
  2558. }
  2559. static void mpegts_free(MpegTSContext *ts)
  2560. {
  2561. int i;
  2562. clear_programs(ts);
  2563. for (i = 0; i < NB_PID_MAX; i++)
  2564. if (ts->pids[i])
  2565. mpegts_close_filter(ts, ts->pids[i]);
  2566. }
  2567. static int mpegts_read_close(AVFormatContext *s)
  2568. {
  2569. MpegTSContext *ts = s->priv_data;
  2570. mpegts_free(ts);
  2571. return 0;
  2572. }
  2573. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2574. int64_t *ppos, int64_t pos_limit)
  2575. {
  2576. MpegTSContext *ts = s->priv_data;
  2577. int64_t pos, timestamp;
  2578. uint8_t buf[TS_PACKET_SIZE];
  2579. int pcr_l, pcr_pid =
  2580. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2581. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2582. pos =
  2583. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2584. ts->raw_packet_size + pos47;
  2585. while(pos < pos_limit) {
  2586. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2587. return AV_NOPTS_VALUE;
  2588. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2589. return AV_NOPTS_VALUE;
  2590. if (buf[0] != 0x47) {
  2591. if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
  2592. return AV_NOPTS_VALUE;
  2593. pos = avio_tell(s->pb);
  2594. continue;
  2595. }
  2596. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2597. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2598. *ppos = pos;
  2599. return timestamp;
  2600. }
  2601. pos += ts->raw_packet_size;
  2602. }
  2603. return AV_NOPTS_VALUE;
  2604. }
  2605. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2606. int64_t *ppos, int64_t pos_limit)
  2607. {
  2608. MpegTSContext *ts = s->priv_data;
  2609. int64_t pos;
  2610. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2611. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2612. ff_read_frame_flush(s);
  2613. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2614. return AV_NOPTS_VALUE;
  2615. while(pos < pos_limit) {
  2616. int ret;
  2617. AVPacket pkt;
  2618. av_init_packet(&pkt);
  2619. ret = av_read_frame(s, &pkt);
  2620. if (ret < 0)
  2621. return AV_NOPTS_VALUE;
  2622. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2623. ff_reduce_index(s, pkt.stream_index);
  2624. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2625. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2626. int64_t dts = pkt.dts;
  2627. *ppos = pkt.pos;
  2628. av_packet_unref(&pkt);
  2629. return dts;
  2630. }
  2631. }
  2632. pos = pkt.pos;
  2633. av_packet_unref(&pkt);
  2634. }
  2635. return AV_NOPTS_VALUE;
  2636. }
  2637. /**************************************************************/
  2638. /* parsing functions - called from other demuxers such as RTP */
  2639. MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
  2640. {
  2641. MpegTSContext *ts;
  2642. ts = av_mallocz(sizeof(MpegTSContext));
  2643. if (!ts)
  2644. return NULL;
  2645. /* no stream case, currently used by RTP */
  2646. ts->raw_packet_size = TS_PACKET_SIZE;
  2647. ts->stream = s;
  2648. ts->auto_guess = 1;
  2649. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2650. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2651. return ts;
  2652. }
  2653. /* return the consumed length if a packet was output, or -1 if no
  2654. * packet is output */
  2655. int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2656. const uint8_t *buf, int len)
  2657. {
  2658. int len1;
  2659. len1 = len;
  2660. ts->pkt = pkt;
  2661. for (;;) {
  2662. ts->stop_parse = 0;
  2663. if (len < TS_PACKET_SIZE)
  2664. return AVERROR_INVALIDDATA;
  2665. if (buf[0] != 0x47) {
  2666. buf++;
  2667. len--;
  2668. } else {
  2669. handle_packet(ts, buf);
  2670. buf += TS_PACKET_SIZE;
  2671. len -= TS_PACKET_SIZE;
  2672. if (ts->stop_parse == 1)
  2673. break;
  2674. }
  2675. }
  2676. return len1 - len;
  2677. }
  2678. void avpriv_mpegts_parse_close(MpegTSContext *ts)
  2679. {
  2680. mpegts_free(ts);
  2681. av_free(ts);
  2682. }
  2683. AVInputFormat ff_mpegts_demuxer = {
  2684. .name = "mpegts",
  2685. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2686. .priv_data_size = sizeof(MpegTSContext),
  2687. .read_probe = mpegts_probe,
  2688. .read_header = mpegts_read_header,
  2689. .read_packet = mpegts_read_packet,
  2690. .read_close = mpegts_read_close,
  2691. .read_timestamp = mpegts_get_dts,
  2692. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2693. .priv_class = &mpegts_class,
  2694. };
  2695. AVInputFormat ff_mpegtsraw_demuxer = {
  2696. .name = "mpegtsraw",
  2697. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2698. .priv_data_size = sizeof(MpegTSContext),
  2699. .read_header = mpegts_read_header,
  2700. .read_packet = mpegts_raw_read_packet,
  2701. .read_close = mpegts_read_close,
  2702. .read_timestamp = mpegts_get_dts,
  2703. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2704. .priv_class = &mpegtsraw_class,
  2705. };