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.

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