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.

2842 lines
94KB

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