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.

2885 lines
95KB

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