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.

3278 lines
110KB

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