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.

2900 lines
96KB

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