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.

2830 lines
93KB

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