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.

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