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.

2824 lines
93KB

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