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.

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