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.

2774 lines
91KB

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