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.

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