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.

2895 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. if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
  1596. st->request_probe = 50;
  1597. }
  1598. break;
  1599. case 0x52: /* stream identifier descriptor */
  1600. st->stream_identifier = 1 + get8(pp, desc_end);
  1601. break;
  1602. case 0x26: /* metadata descriptor */
  1603. if (get16(pp, desc_end) == 0xFFFF)
  1604. *pp += 4;
  1605. if (get8(pp, desc_end) == 0xFF) {
  1606. st->codecpar->codec_tag = bytestream_get_le32(pp);
  1607. if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
  1608. mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
  1609. }
  1610. break;
  1611. case 0x7f: /* DVB extension descriptor */
  1612. ext_desc_tag = get8(pp, desc_end);
  1613. if (ext_desc_tag < 0)
  1614. return AVERROR_INVALIDDATA;
  1615. if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
  1616. ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
  1617. if (!st->codecpar->extradata) {
  1618. st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
  1619. AV_INPUT_BUFFER_PADDING_SIZE);
  1620. if (!st->codecpar->extradata)
  1621. return AVERROR(ENOMEM);
  1622. st->codecpar->extradata_size = sizeof(opus_default_extradata);
  1623. memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
  1624. channel_config_code = get8(pp, desc_end);
  1625. if (channel_config_code < 0)
  1626. return AVERROR_INVALIDDATA;
  1627. if (channel_config_code <= 0x8) {
  1628. st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
  1629. st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
  1630. st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
  1631. st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
  1632. memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
  1633. } else {
  1634. avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
  1635. }
  1636. st->need_parsing = AVSTREAM_PARSE_FULL;
  1637. st->internal->need_context_update = 1;
  1638. }
  1639. }
  1640. break;
  1641. default:
  1642. break;
  1643. }
  1644. *pp = desc_end;
  1645. return 0;
  1646. }
  1647. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1648. {
  1649. MpegTSContext *ts = filter->u.section_filter.opaque;
  1650. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1651. SectionHeader h1, *h = &h1;
  1652. PESContext *pes;
  1653. AVStream *st;
  1654. const uint8_t *p, *p_end, *desc_list_end;
  1655. int program_info_length, pcr_pid, pid, stream_type;
  1656. int desc_list_len;
  1657. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1658. int mp4_descr_count = 0;
  1659. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1660. int i;
  1661. av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
  1662. hex_dump_debug(ts->stream, section, section_len);
  1663. p_end = section + section_len - 4;
  1664. p = section;
  1665. if (parse_section_header(h, &p, p_end) < 0)
  1666. return;
  1667. if (skip_identical(h, tssf))
  1668. return;
  1669. av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d\n",
  1670. h->id, h->sec_num, h->last_sec_num, h->version);
  1671. if (h->tid != PMT_TID)
  1672. return;
  1673. if (!ts->scan_all_pmts && ts->skip_changes)
  1674. return;
  1675. if (!ts->skip_clear)
  1676. clear_program(ts, h->id);
  1677. pcr_pid = get16(&p, p_end);
  1678. if (pcr_pid < 0)
  1679. return;
  1680. pcr_pid &= 0x1fff;
  1681. add_pid_to_pmt(ts, h->id, pcr_pid);
  1682. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1683. av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
  1684. program_info_length = get16(&p, p_end);
  1685. if (program_info_length < 0)
  1686. return;
  1687. program_info_length &= 0xfff;
  1688. while (program_info_length >= 2) {
  1689. uint8_t tag, len;
  1690. tag = get8(&p, p_end);
  1691. len = get8(&p, p_end);
  1692. av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
  1693. if (len > program_info_length - 2)
  1694. // something else is broken, exit the program_descriptors_loop
  1695. break;
  1696. program_info_length -= len + 2;
  1697. if (tag == 0x1d) { // IOD descriptor
  1698. get8(&p, p_end); // scope
  1699. get8(&p, p_end); // label
  1700. len -= 2;
  1701. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1702. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1703. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1704. prog_reg_desc = bytestream_get_le32(&p);
  1705. len -= 4;
  1706. }
  1707. p += len;
  1708. }
  1709. p += program_info_length;
  1710. if (p >= p_end)
  1711. goto out;
  1712. // stop parsing after pmt, we found header
  1713. if (!ts->stream->nb_streams)
  1714. ts->stop_parse = 2;
  1715. set_pmt_found(ts, h->id);
  1716. for (;;) {
  1717. st = 0;
  1718. pes = NULL;
  1719. stream_type = get8(&p, p_end);
  1720. if (stream_type < 0)
  1721. break;
  1722. pid = get16(&p, p_end);
  1723. if (pid < 0)
  1724. goto out;
  1725. pid &= 0x1fff;
  1726. if (pid == ts->current_pid)
  1727. goto out;
  1728. /* now create stream */
  1729. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1730. pes = ts->pids[pid]->u.pes_filter.opaque;
  1731. if (!pes->st) {
  1732. pes->st = avformat_new_stream(pes->stream, NULL);
  1733. if (!pes->st)
  1734. goto out;
  1735. pes->st->id = pes->pid;
  1736. }
  1737. st = pes->st;
  1738. } else if (stream_type != 0x13) {
  1739. if (ts->pids[pid])
  1740. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1741. pes = add_pes_stream(ts, pid, pcr_pid);
  1742. if (pes) {
  1743. st = avformat_new_stream(pes->stream, NULL);
  1744. if (!st)
  1745. goto out;
  1746. st->id = pes->pid;
  1747. }
  1748. } else {
  1749. int idx = ff_find_stream_index(ts->stream, pid);
  1750. if (idx >= 0) {
  1751. st = ts->stream->streams[idx];
  1752. } else {
  1753. st = avformat_new_stream(ts->stream, NULL);
  1754. if (!st)
  1755. goto out;
  1756. st->id = pid;
  1757. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  1758. }
  1759. }
  1760. if (!st)
  1761. goto out;
  1762. if (pes && !pes->stream_type)
  1763. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1764. add_pid_to_pmt(ts, h->id, pid);
  1765. av_program_add_stream_index(ts->stream, h->id, st->index);
  1766. desc_list_len = get16(&p, p_end);
  1767. if (desc_list_len < 0)
  1768. goto out;
  1769. desc_list_len &= 0xfff;
  1770. desc_list_end = p + desc_list_len;
  1771. if (desc_list_end > p_end)
  1772. goto out;
  1773. for (;;) {
  1774. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1775. desc_list_end, mp4_descr,
  1776. mp4_descr_count, pid, ts) < 0)
  1777. break;
  1778. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1779. stream_type == 0x83 && pes->sub_st) {
  1780. av_program_add_stream_index(ts->stream, h->id,
  1781. pes->sub_st->index);
  1782. pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
  1783. }
  1784. }
  1785. p = desc_list_end;
  1786. }
  1787. if (!ts->pids[pcr_pid])
  1788. mpegts_open_pcr_filter(ts, pcr_pid);
  1789. out:
  1790. for (i = 0; i < mp4_descr_count; i++)
  1791. av_free(mp4_descr[i].dec_config_descr);
  1792. }
  1793. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1794. {
  1795. MpegTSContext *ts = filter->u.section_filter.opaque;
  1796. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1797. SectionHeader h1, *h = &h1;
  1798. const uint8_t *p, *p_end;
  1799. int sid, pmt_pid;
  1800. AVProgram *program;
  1801. av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
  1802. hex_dump_debug(ts->stream, section, section_len);
  1803. p_end = section + section_len - 4;
  1804. p = section;
  1805. if (parse_section_header(h, &p, p_end) < 0)
  1806. return;
  1807. if (h->tid != PAT_TID)
  1808. return;
  1809. if (ts->skip_changes)
  1810. return;
  1811. if (skip_identical(h, tssf))
  1812. return;
  1813. ts->stream->ts_id = h->id;
  1814. clear_programs(ts);
  1815. for (;;) {
  1816. sid = get16(&p, p_end);
  1817. if (sid < 0)
  1818. break;
  1819. pmt_pid = get16(&p, p_end);
  1820. if (pmt_pid < 0)
  1821. break;
  1822. pmt_pid &= 0x1fff;
  1823. if (pmt_pid == ts->current_pid)
  1824. break;
  1825. av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1826. if (sid == 0x0000) {
  1827. /* NIT info */
  1828. } else {
  1829. MpegTSFilter *fil = ts->pids[pmt_pid];
  1830. program = av_new_program(ts->stream, sid);
  1831. if (program) {
  1832. program->program_num = sid;
  1833. program->pmt_pid = pmt_pid;
  1834. }
  1835. if (fil)
  1836. if ( fil->type != MPEGTS_SECTION
  1837. || fil->pid != pmt_pid
  1838. || fil->u.section_filter.section_cb != pmt_cb)
  1839. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1840. if (!ts->pids[pmt_pid])
  1841. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1842. add_pat_entry(ts, sid);
  1843. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1844. add_pid_to_pmt(ts, sid, pmt_pid);
  1845. }
  1846. }
  1847. if (sid < 0) {
  1848. int i,j;
  1849. for (j=0; j<ts->stream->nb_programs; j++) {
  1850. for (i = 0; i < ts->nb_prg; i++)
  1851. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1852. break;
  1853. if (i==ts->nb_prg && !ts->skip_clear)
  1854. clear_avprogram(ts, ts->stream->programs[j]->id);
  1855. }
  1856. }
  1857. }
  1858. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1859. {
  1860. MpegTSContext *ts = filter->u.section_filter.opaque;
  1861. MpegTSSectionFilter *tssf = &filter->u.section_filter;
  1862. SectionHeader h1, *h = &h1;
  1863. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1864. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1865. char *name, *provider_name;
  1866. av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
  1867. hex_dump_debug(ts->stream, section, section_len);
  1868. p_end = section + section_len - 4;
  1869. p = section;
  1870. if (parse_section_header(h, &p, p_end) < 0)
  1871. return;
  1872. if (h->tid != SDT_TID)
  1873. return;
  1874. if (ts->skip_changes)
  1875. return;
  1876. if (skip_identical(h, tssf))
  1877. return;
  1878. onid = get16(&p, p_end);
  1879. if (onid < 0)
  1880. return;
  1881. val = get8(&p, p_end);
  1882. if (val < 0)
  1883. return;
  1884. for (;;) {
  1885. sid = get16(&p, p_end);
  1886. if (sid < 0)
  1887. break;
  1888. val = get8(&p, p_end);
  1889. if (val < 0)
  1890. break;
  1891. desc_list_len = get16(&p, p_end);
  1892. if (desc_list_len < 0)
  1893. break;
  1894. desc_list_len &= 0xfff;
  1895. desc_list_end = p + desc_list_len;
  1896. if (desc_list_end > p_end)
  1897. break;
  1898. for (;;) {
  1899. desc_tag = get8(&p, desc_list_end);
  1900. if (desc_tag < 0)
  1901. break;
  1902. desc_len = get8(&p, desc_list_end);
  1903. desc_end = p + desc_len;
  1904. if (desc_len < 0 || desc_end > desc_list_end)
  1905. break;
  1906. av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
  1907. desc_tag, desc_len);
  1908. switch (desc_tag) {
  1909. case 0x48:
  1910. service_type = get8(&p, p_end);
  1911. if (service_type < 0)
  1912. break;
  1913. provider_name = getstr8(&p, p_end);
  1914. if (!provider_name)
  1915. break;
  1916. name = getstr8(&p, p_end);
  1917. if (name) {
  1918. AVProgram *program = av_new_program(ts->stream, sid);
  1919. if (program) {
  1920. av_dict_set(&program->metadata, "service_name", name, 0);
  1921. av_dict_set(&program->metadata, "service_provider",
  1922. provider_name, 0);
  1923. }
  1924. }
  1925. av_free(name);
  1926. av_free(provider_name);
  1927. break;
  1928. default:
  1929. break;
  1930. }
  1931. p = desc_end;
  1932. }
  1933. p = desc_list_end;
  1934. }
  1935. }
  1936. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1937. const uint8_t *packet);
  1938. /* handle one TS packet */
  1939. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1940. {
  1941. MpegTSFilter *tss;
  1942. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1943. has_adaptation, has_payload;
  1944. const uint8_t *p, *p_end;
  1945. int64_t pos;
  1946. pid = AV_RB16(packet + 1) & 0x1fff;
  1947. if (pid && discard_pid(ts, pid))
  1948. return 0;
  1949. is_start = packet[1] & 0x40;
  1950. tss = ts->pids[pid];
  1951. if (ts->auto_guess && !tss && is_start) {
  1952. add_pes_stream(ts, pid, -1);
  1953. tss = ts->pids[pid];
  1954. }
  1955. if (!tss)
  1956. return 0;
  1957. ts->current_pid = pid;
  1958. afc = (packet[3] >> 4) & 3;
  1959. if (afc == 0) /* reserved value */
  1960. return 0;
  1961. has_adaptation = afc & 2;
  1962. has_payload = afc & 1;
  1963. is_discontinuity = has_adaptation &&
  1964. packet[4] != 0 && /* with length > 0 */
  1965. (packet[5] & 0x80); /* and discontinuity indicated */
  1966. /* continuity check (currently not used) */
  1967. cc = (packet[3] & 0xf);
  1968. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1969. cc_ok = pid == 0x1FFF || // null packet PID
  1970. is_discontinuity ||
  1971. tss->last_cc < 0 ||
  1972. expected_cc == cc;
  1973. tss->last_cc = cc;
  1974. if (!cc_ok) {
  1975. av_log(ts->stream, AV_LOG_DEBUG,
  1976. "Continuity check failed for pid %d expected %d got %d\n",
  1977. pid, expected_cc, cc);
  1978. if (tss->type == MPEGTS_PES) {
  1979. PESContext *pc = tss->u.pes_filter.opaque;
  1980. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1981. }
  1982. }
  1983. p = packet + 4;
  1984. if (has_adaptation) {
  1985. int64_t pcr_h;
  1986. int pcr_l;
  1987. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1988. tss->last_pcr = pcr_h * 300 + pcr_l;
  1989. /* skip adaptation field */
  1990. p += p[0] + 1;
  1991. }
  1992. /* if past the end of packet, ignore */
  1993. p_end = packet + TS_PACKET_SIZE;
  1994. if (p >= p_end || !has_payload)
  1995. return 0;
  1996. pos = avio_tell(ts->stream->pb);
  1997. if (pos >= 0) {
  1998. av_assert0(pos >= TS_PACKET_SIZE);
  1999. ts->pos47_full = pos - TS_PACKET_SIZE;
  2000. }
  2001. if (tss->type == MPEGTS_SECTION) {
  2002. if (is_start) {
  2003. /* pointer field present */
  2004. len = *p++;
  2005. if (len > p_end - p)
  2006. return 0;
  2007. if (len && cc_ok) {
  2008. /* write remaining section bytes */
  2009. write_section_data(ts, tss,
  2010. p, len, 0);
  2011. /* check whether filter has been closed */
  2012. if (!ts->pids[pid])
  2013. return 0;
  2014. }
  2015. p += len;
  2016. if (p < p_end) {
  2017. write_section_data(ts, tss,
  2018. p, p_end - p, 1);
  2019. }
  2020. } else {
  2021. if (cc_ok) {
  2022. write_section_data(ts, tss,
  2023. p, p_end - p, 0);
  2024. }
  2025. }
  2026. // stop find_stream_info from waiting for more streams
  2027. // when all programs have received a PMT
  2028. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
  2029. int i;
  2030. for (i = 0; i < ts->nb_prg; i++) {
  2031. if (!ts->prg[i].pmt_found)
  2032. break;
  2033. }
  2034. if (i == ts->nb_prg && ts->nb_prg > 0) {
  2035. int types = 0;
  2036. for (i = 0; i < ts->stream->nb_streams; i++) {
  2037. AVStream *st = ts->stream->streams[i];
  2038. types |= 1<<st->codecpar->codec_type;
  2039. }
  2040. if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
  2041. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  2042. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  2043. }
  2044. }
  2045. }
  2046. } else {
  2047. int ret;
  2048. // Note: The position here points actually behind the current packet.
  2049. if (tss->type == MPEGTS_PES) {
  2050. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  2051. pos - ts->raw_packet_size)) < 0)
  2052. return ret;
  2053. }
  2054. }
  2055. return 0;
  2056. }
  2057. static void reanalyze(MpegTSContext *ts) {
  2058. AVIOContext *pb = ts->stream->pb;
  2059. int64_t pos = avio_tell(pb);
  2060. if (pos < 0)
  2061. return;
  2062. pos -= ts->pos47_full;
  2063. if (pos == TS_PACKET_SIZE) {
  2064. ts->size_stat[0] ++;
  2065. } else if (pos == TS_DVHS_PACKET_SIZE) {
  2066. ts->size_stat[1] ++;
  2067. } else if (pos == TS_FEC_PACKET_SIZE) {
  2068. ts->size_stat[2] ++;
  2069. }
  2070. ts->size_stat_count ++;
  2071. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  2072. int newsize = 0;
  2073. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  2074. newsize = TS_PACKET_SIZE;
  2075. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  2076. newsize = TS_DVHS_PACKET_SIZE;
  2077. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  2078. newsize = TS_FEC_PACKET_SIZE;
  2079. }
  2080. if (newsize && newsize != ts->raw_packet_size) {
  2081. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  2082. ts->raw_packet_size = newsize;
  2083. }
  2084. ts->size_stat_count = 0;
  2085. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  2086. }
  2087. }
  2088. /* XXX: try to find a better synchro over several packets (use
  2089. * get_packet_size() ?) */
  2090. static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
  2091. {
  2092. MpegTSContext *ts = s->priv_data;
  2093. AVIOContext *pb = s->pb;
  2094. int c, i;
  2095. uint64_t pos = avio_tell(pb);
  2096. avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
  2097. //Special case for files like 01c56b0dc1.ts
  2098. if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
  2099. avio_seek(pb, 12, SEEK_CUR);
  2100. return 0;
  2101. }
  2102. for (i = 0; i < ts->resync_size; i++) {
  2103. c = avio_r8(pb);
  2104. if (avio_feof(pb))
  2105. return AVERROR_EOF;
  2106. if (c == 0x47) {
  2107. avio_seek(pb, -1, SEEK_CUR);
  2108. reanalyze(s->priv_data);
  2109. return 0;
  2110. }
  2111. }
  2112. av_log(s, AV_LOG_ERROR,
  2113. "max resync size reached, could not find sync byte\n");
  2114. /* no sync found */
  2115. return AVERROR_INVALIDDATA;
  2116. }
  2117. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  2118. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  2119. const uint8_t **data)
  2120. {
  2121. AVIOContext *pb = s->pb;
  2122. int len;
  2123. for (;;) {
  2124. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  2125. if (len != TS_PACKET_SIZE)
  2126. return len < 0 ? len : AVERROR_EOF;
  2127. /* check packet sync byte */
  2128. if ((*data)[0] != 0x47) {
  2129. /* find a new packet start */
  2130. if (mpegts_resync(s, raw_packet_size, *data) < 0)
  2131. return AVERROR(EAGAIN);
  2132. else
  2133. continue;
  2134. } else {
  2135. break;
  2136. }
  2137. }
  2138. return 0;
  2139. }
  2140. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  2141. {
  2142. AVIOContext *pb = s->pb;
  2143. int skip = raw_packet_size - TS_PACKET_SIZE;
  2144. if (skip > 0)
  2145. avio_skip(pb, skip);
  2146. }
  2147. static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
  2148. {
  2149. AVFormatContext *s = ts->stream;
  2150. uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
  2151. const uint8_t *data;
  2152. int64_t packet_num;
  2153. int ret = 0;
  2154. if (avio_tell(s->pb) != ts->last_pos) {
  2155. int i;
  2156. av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
  2157. /* seek detected, flush pes buffer */
  2158. for (i = 0; i < NB_PID_MAX; i++) {
  2159. if (ts->pids[i]) {
  2160. if (ts->pids[i]->type == MPEGTS_PES) {
  2161. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2162. av_buffer_unref(&pes->buffer);
  2163. pes->data_index = 0;
  2164. pes->state = MPEGTS_SKIP; /* skip until pes header */
  2165. } else if (ts->pids[i]->type == MPEGTS_SECTION) {
  2166. ts->pids[i]->u.section_filter.last_ver = -1;
  2167. }
  2168. ts->pids[i]->last_cc = -1;
  2169. ts->pids[i]->last_pcr = -1;
  2170. }
  2171. }
  2172. }
  2173. ts->stop_parse = 0;
  2174. packet_num = 0;
  2175. memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  2176. for (;;) {
  2177. packet_num++;
  2178. if (nb_packets != 0 && packet_num >= nb_packets ||
  2179. ts->stop_parse > 1) {
  2180. ret = AVERROR(EAGAIN);
  2181. break;
  2182. }
  2183. if (ts->stop_parse > 0)
  2184. break;
  2185. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2186. if (ret != 0)
  2187. break;
  2188. ret = handle_packet(ts, data);
  2189. finished_reading_packet(s, ts->raw_packet_size);
  2190. if (ret != 0)
  2191. break;
  2192. }
  2193. ts->last_pos = avio_tell(s->pb);
  2194. return ret;
  2195. }
  2196. static int mpegts_probe(AVProbeData *p)
  2197. {
  2198. const int size = p->buf_size;
  2199. int maxscore = 0;
  2200. int sumscore = 0;
  2201. int i;
  2202. int check_count = size / TS_FEC_PACKET_SIZE;
  2203. #define CHECK_COUNT 10
  2204. #define CHECK_BLOCK 100
  2205. if (!check_count)
  2206. return 0;
  2207. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2208. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2209. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
  2210. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
  2211. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
  2212. score = FFMAX3(score, dvhs_score, fec_score);
  2213. sumscore += score;
  2214. maxscore = FFMAX(maxscore, score);
  2215. }
  2216. sumscore = sumscore * CHECK_COUNT / check_count;
  2217. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2218. ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2219. if (check_count >= CHECK_COUNT && sumscore > 6) {
  2220. return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2221. } else if (check_count >= CHECK_COUNT && maxscore > 6) {
  2222. return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2223. } else if (sumscore > 6) {
  2224. return 2;
  2225. } else {
  2226. return 0;
  2227. }
  2228. }
  2229. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2230. * (-1) if not available */
  2231. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2232. {
  2233. int afc, len, flags;
  2234. const uint8_t *p;
  2235. unsigned int v;
  2236. afc = (packet[3] >> 4) & 3;
  2237. if (afc <= 1)
  2238. return AVERROR_INVALIDDATA;
  2239. p = packet + 4;
  2240. len = p[0];
  2241. p++;
  2242. if (len == 0)
  2243. return AVERROR_INVALIDDATA;
  2244. flags = *p++;
  2245. len--;
  2246. if (!(flags & 0x10))
  2247. return AVERROR_INVALIDDATA;
  2248. if (len < 6)
  2249. return AVERROR_INVALIDDATA;
  2250. v = AV_RB32(p);
  2251. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2252. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2253. return 0;
  2254. }
  2255. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2256. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2257. * probe buffer usually is big enough. Only warn if the seek failed
  2258. * on files where the seek should work. */
  2259. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2260. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2261. }
  2262. static int mpegts_read_header(AVFormatContext *s)
  2263. {
  2264. MpegTSContext *ts = s->priv_data;
  2265. AVIOContext *pb = s->pb;
  2266. uint8_t buf[8 * 1024] = {0};
  2267. int len;
  2268. int64_t pos, probesize = s->probesize;
  2269. if (ffio_ensure_seekback(pb, probesize) < 0)
  2270. av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
  2271. /* read the first 8192 bytes to get packet size */
  2272. pos = avio_tell(pb);
  2273. len = avio_read(pb, buf, sizeof(buf));
  2274. ts->raw_packet_size = get_packet_size(buf, len);
  2275. if (ts->raw_packet_size <= 0) {
  2276. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2277. ts->raw_packet_size = TS_PACKET_SIZE;
  2278. }
  2279. ts->stream = s;
  2280. ts->auto_guess = 0;
  2281. if (s->iformat == &ff_mpegts_demuxer) {
  2282. /* normal demux */
  2283. /* first do a scan to get all the services */
  2284. seek_back(s, pb, pos);
  2285. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2286. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2287. handle_packets(ts, probesize / ts->raw_packet_size);
  2288. /* if could not find service, enable auto_guess */
  2289. ts->auto_guess = 1;
  2290. av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
  2291. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2292. } else {
  2293. AVStream *st;
  2294. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2295. int64_t pcrs[2], pcr_h;
  2296. int packet_count[2];
  2297. uint8_t packet[TS_PACKET_SIZE];
  2298. const uint8_t *data;
  2299. /* only read packets */
  2300. st = avformat_new_stream(s, NULL);
  2301. if (!st)
  2302. return AVERROR(ENOMEM);
  2303. avpriv_set_pts_info(st, 60, 1, 27000000);
  2304. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2305. st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
  2306. /* we iterate until we find two PCRs to estimate the bitrate */
  2307. pcr_pid = -1;
  2308. nb_pcrs = 0;
  2309. nb_packets = 0;
  2310. for (;;) {
  2311. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2312. if (ret < 0)
  2313. return ret;
  2314. pid = AV_RB16(data + 1) & 0x1fff;
  2315. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2316. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2317. finished_reading_packet(s, ts->raw_packet_size);
  2318. pcr_pid = pid;
  2319. packet_count[nb_pcrs] = nb_packets;
  2320. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2321. nb_pcrs++;
  2322. if (nb_pcrs >= 2)
  2323. break;
  2324. } else {
  2325. finished_reading_packet(s, ts->raw_packet_size);
  2326. }
  2327. nb_packets++;
  2328. }
  2329. /* NOTE1: the bitrate is computed without the FEC */
  2330. /* NOTE2: it is only the bitrate of the start of the stream */
  2331. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2332. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2333. s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
  2334. st->codecpar->bit_rate = s->bit_rate;
  2335. st->start_time = ts->cur_pcr;
  2336. av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
  2337. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2338. }
  2339. seek_back(s, pb, pos);
  2340. return 0;
  2341. }
  2342. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2343. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2344. {
  2345. MpegTSContext *ts = s->priv_data;
  2346. int ret, i;
  2347. int64_t pcr_h, next_pcr_h, pos;
  2348. int pcr_l, next_pcr_l;
  2349. uint8_t pcr_buf[12];
  2350. const uint8_t *data;
  2351. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2352. return AVERROR(ENOMEM);
  2353. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2354. pkt->pos = avio_tell(s->pb);
  2355. if (ret < 0) {
  2356. av_packet_unref(pkt);
  2357. return ret;
  2358. }
  2359. if (data != pkt->data)
  2360. memcpy(pkt->data, data, ts->raw_packet_size);
  2361. finished_reading_packet(s, ts->raw_packet_size);
  2362. if (ts->mpeg2ts_compute_pcr) {
  2363. /* compute exact PCR for each packet */
  2364. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2365. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2366. pos = avio_tell(s->pb);
  2367. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2368. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2369. avio_read(s->pb, pcr_buf, 12);
  2370. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2371. /* XXX: not precise enough */
  2372. ts->pcr_incr =
  2373. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2374. (i + 1);
  2375. break;
  2376. }
  2377. }
  2378. avio_seek(s->pb, pos, SEEK_SET);
  2379. /* no next PCR found: we use previous increment */
  2380. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2381. }
  2382. pkt->pts = ts->cur_pcr;
  2383. pkt->duration = ts->pcr_incr;
  2384. ts->cur_pcr += ts->pcr_incr;
  2385. }
  2386. pkt->stream_index = 0;
  2387. return 0;
  2388. }
  2389. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2390. {
  2391. MpegTSContext *ts = s->priv_data;
  2392. int ret, i;
  2393. pkt->size = -1;
  2394. ts->pkt = pkt;
  2395. ret = handle_packets(ts, 0);
  2396. if (ret < 0) {
  2397. av_packet_unref(ts->pkt);
  2398. /* flush pes data left */
  2399. for (i = 0; i < NB_PID_MAX; i++)
  2400. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2401. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2402. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2403. ret = new_pes_packet(pes, pkt);
  2404. if (ret < 0)
  2405. return ret;
  2406. pes->state = MPEGTS_SKIP;
  2407. ret = 0;
  2408. break;
  2409. }
  2410. }
  2411. }
  2412. if (!ret && pkt->size < 0)
  2413. ret = AVERROR_INVALIDDATA;
  2414. return ret;
  2415. }
  2416. static void mpegts_free(MpegTSContext *ts)
  2417. {
  2418. int i;
  2419. clear_programs(ts);
  2420. for (i = 0; i < NB_PID_MAX; i++)
  2421. if (ts->pids[i])
  2422. mpegts_close_filter(ts, ts->pids[i]);
  2423. }
  2424. static int mpegts_read_close(AVFormatContext *s)
  2425. {
  2426. MpegTSContext *ts = s->priv_data;
  2427. mpegts_free(ts);
  2428. return 0;
  2429. }
  2430. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2431. int64_t *ppos, int64_t pos_limit)
  2432. {
  2433. MpegTSContext *ts = s->priv_data;
  2434. int64_t pos, timestamp;
  2435. uint8_t buf[TS_PACKET_SIZE];
  2436. int pcr_l, pcr_pid =
  2437. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2438. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2439. pos =
  2440. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2441. ts->raw_packet_size + pos47;
  2442. while(pos < pos_limit) {
  2443. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2444. return AV_NOPTS_VALUE;
  2445. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2446. return AV_NOPTS_VALUE;
  2447. if (buf[0] != 0x47) {
  2448. if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
  2449. return AV_NOPTS_VALUE;
  2450. pos = avio_tell(s->pb);
  2451. continue;
  2452. }
  2453. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2454. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2455. *ppos = pos;
  2456. return timestamp;
  2457. }
  2458. pos += ts->raw_packet_size;
  2459. }
  2460. return AV_NOPTS_VALUE;
  2461. }
  2462. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2463. int64_t *ppos, int64_t pos_limit)
  2464. {
  2465. MpegTSContext *ts = s->priv_data;
  2466. int64_t pos;
  2467. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2468. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2469. ff_read_frame_flush(s);
  2470. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2471. return AV_NOPTS_VALUE;
  2472. while(pos < pos_limit) {
  2473. int ret;
  2474. AVPacket pkt;
  2475. av_init_packet(&pkt);
  2476. ret = av_read_frame(s, &pkt);
  2477. if (ret < 0)
  2478. return AV_NOPTS_VALUE;
  2479. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2480. ff_reduce_index(s, pkt.stream_index);
  2481. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2482. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2483. int64_t dts = pkt.dts;
  2484. *ppos = pkt.pos;
  2485. av_packet_unref(&pkt);
  2486. return dts;
  2487. }
  2488. }
  2489. pos = pkt.pos;
  2490. av_packet_unref(&pkt);
  2491. }
  2492. return AV_NOPTS_VALUE;
  2493. }
  2494. /**************************************************************/
  2495. /* parsing functions - called from other demuxers such as RTP */
  2496. MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
  2497. {
  2498. MpegTSContext *ts;
  2499. ts = av_mallocz(sizeof(MpegTSContext));
  2500. if (!ts)
  2501. return NULL;
  2502. /* no stream case, currently used by RTP */
  2503. ts->raw_packet_size = TS_PACKET_SIZE;
  2504. ts->stream = s;
  2505. ts->auto_guess = 1;
  2506. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2507. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2508. return ts;
  2509. }
  2510. /* return the consumed length if a packet was output, or -1 if no
  2511. * packet is output */
  2512. int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2513. const uint8_t *buf, int len)
  2514. {
  2515. int len1;
  2516. len1 = len;
  2517. ts->pkt = pkt;
  2518. for (;;) {
  2519. ts->stop_parse = 0;
  2520. if (len < TS_PACKET_SIZE)
  2521. return AVERROR_INVALIDDATA;
  2522. if (buf[0] != 0x47) {
  2523. buf++;
  2524. len--;
  2525. } else {
  2526. handle_packet(ts, buf);
  2527. buf += TS_PACKET_SIZE;
  2528. len -= TS_PACKET_SIZE;
  2529. if (ts->stop_parse == 1)
  2530. break;
  2531. }
  2532. }
  2533. return len1 - len;
  2534. }
  2535. void avpriv_mpegts_parse_close(MpegTSContext *ts)
  2536. {
  2537. mpegts_free(ts);
  2538. av_free(ts);
  2539. }
  2540. AVInputFormat ff_mpegts_demuxer = {
  2541. .name = "mpegts",
  2542. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2543. .priv_data_size = sizeof(MpegTSContext),
  2544. .read_probe = mpegts_probe,
  2545. .read_header = mpegts_read_header,
  2546. .read_packet = mpegts_read_packet,
  2547. .read_close = mpegts_read_close,
  2548. .read_timestamp = mpegts_get_dts,
  2549. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2550. .priv_class = &mpegts_class,
  2551. };
  2552. AVInputFormat ff_mpegtsraw_demuxer = {
  2553. .name = "mpegtsraw",
  2554. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2555. .priv_data_size = sizeof(MpegTSContext),
  2556. .read_header = mpegts_read_header,
  2557. .read_packet = mpegts_raw_read_packet,
  2558. .read_close = mpegts_read_close,
  2559. .read_timestamp = mpegts_get_dts,
  2560. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2561. .priv_class = &mpegtsraw_class,
  2562. };