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.

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