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.

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