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.

3079 lines
103KB

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