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.

2789 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_stream_cnt[9] = {
  1342. 1, 1, 1, 2, 2, 3, 4, 4, 5,
  1343. };
  1344. static const uint8_t opus_channel_map[8][8] = {
  1345. { 0 },
  1346. { 0,1 },
  1347. { 0,2,1 },
  1348. { 0,1,2,3 },
  1349. { 0,4,1,2,3 },
  1350. { 0,4,1,2,3,5 },
  1351. { 0,4,1,2,3,5,6 },
  1352. { 0,6,1,2,3,4,5,7 },
  1353. };
  1354. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1355. const uint8_t **pp, const uint8_t *desc_list_end,
  1356. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1357. MpegTSContext *ts)
  1358. {
  1359. const uint8_t *desc_end;
  1360. int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
  1361. char language[252];
  1362. int i;
  1363. desc_tag = get8(pp, desc_list_end);
  1364. if (desc_tag < 0)
  1365. return AVERROR_INVALIDDATA;
  1366. desc_len = get8(pp, desc_list_end);
  1367. if (desc_len < 0)
  1368. return AVERROR_INVALIDDATA;
  1369. desc_end = *pp + desc_len;
  1370. if (desc_end > desc_list_end)
  1371. return AVERROR_INVALIDDATA;
  1372. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1373. if ((st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
  1374. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1375. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1376. switch (desc_tag) {
  1377. case 0x1E: /* SL descriptor */
  1378. desc_es_id = get16(pp, desc_end);
  1379. if (desc_es_id < 0)
  1380. break;
  1381. if (ts && ts->pids[pid])
  1382. ts->pids[pid]->es_id = desc_es_id;
  1383. for (i = 0; i < mp4_descr_count; i++)
  1384. if (mp4_descr[i].dec_config_descr_len &&
  1385. mp4_descr[i].es_id == desc_es_id) {
  1386. AVIOContext pb;
  1387. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1388. mp4_descr[i].dec_config_descr_len, 0,
  1389. NULL, NULL, NULL, NULL);
  1390. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1391. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1392. st->codec->extradata_size > 0)
  1393. st->need_parsing = 0;
  1394. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1395. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1396. }
  1397. break;
  1398. case 0x1F: /* FMC descriptor */
  1399. if (get16(pp, desc_end) < 0)
  1400. break;
  1401. if (mp4_descr_count > 0 &&
  1402. (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe > 0) &&
  1403. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1404. AVIOContext pb;
  1405. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1406. mp4_descr->dec_config_descr_len, 0,
  1407. NULL, NULL, NULL, NULL);
  1408. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1409. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1410. st->codec->extradata_size > 0) {
  1411. st->request_probe = st->need_parsing = 0;
  1412. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1413. }
  1414. }
  1415. break;
  1416. case 0x56: /* DVB teletext descriptor */
  1417. {
  1418. uint8_t *extradata = NULL;
  1419. int language_count = desc_len / 5;
  1420. if (desc_len > 0 && desc_len % 5 != 0)
  1421. return AVERROR_INVALIDDATA;
  1422. if (language_count > 0) {
  1423. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1424. if (language_count > sizeof(language) / 4) {
  1425. language_count = sizeof(language) / 4;
  1426. }
  1427. if (st->codec->extradata == NULL) {
  1428. if (ff_alloc_extradata(st->codec, language_count * 2)) {
  1429. return AVERROR(ENOMEM);
  1430. }
  1431. }
  1432. if (st->codec->extradata_size < language_count * 2)
  1433. return AVERROR_INVALIDDATA;
  1434. extradata = st->codec->extradata;
  1435. for (i = 0; i < language_count; i++) {
  1436. language[i * 4 + 0] = get8(pp, desc_end);
  1437. language[i * 4 + 1] = get8(pp, desc_end);
  1438. language[i * 4 + 2] = get8(pp, desc_end);
  1439. language[i * 4 + 3] = ',';
  1440. memcpy(extradata, *pp, 2);
  1441. extradata += 2;
  1442. *pp += 2;
  1443. }
  1444. language[i * 4 - 1] = 0;
  1445. av_dict_set(&st->metadata, "language", language, 0);
  1446. }
  1447. }
  1448. break;
  1449. case 0x59: /* subtitling descriptor */
  1450. {
  1451. /* 8 bytes per DVB subtitle substream data:
  1452. * ISO_639_language_code (3 bytes),
  1453. * subtitling_type (1 byte),
  1454. * composition_page_id (2 bytes),
  1455. * ancillary_page_id (2 bytes) */
  1456. int language_count = desc_len / 8;
  1457. if (desc_len > 0 && desc_len % 8 != 0)
  1458. return AVERROR_INVALIDDATA;
  1459. if (language_count > 1) {
  1460. avpriv_request_sample(fc, "DVB subtitles with multiple languages");
  1461. }
  1462. if (language_count > 0) {
  1463. uint8_t *extradata;
  1464. /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
  1465. if (language_count > sizeof(language) / 4) {
  1466. language_count = sizeof(language) / 4;
  1467. }
  1468. if (st->codec->extradata == NULL) {
  1469. if (ff_alloc_extradata(st->codec, language_count * 5)) {
  1470. return AVERROR(ENOMEM);
  1471. }
  1472. }
  1473. if (st->codec->extradata_size < language_count * 5)
  1474. return AVERROR_INVALIDDATA;
  1475. extradata = st->codec->extradata;
  1476. for (i = 0; i < language_count; i++) {
  1477. language[i * 4 + 0] = get8(pp, desc_end);
  1478. language[i * 4 + 1] = get8(pp, desc_end);
  1479. language[i * 4 + 2] = get8(pp, desc_end);
  1480. language[i * 4 + 3] = ',';
  1481. /* hearing impaired subtitles detection using subtitling_type */
  1482. switch (*pp[0]) {
  1483. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1484. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1485. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1486. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1487. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1488. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1489. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1490. break;
  1491. }
  1492. extradata[4] = get8(pp, desc_end); /* subtitling_type */
  1493. memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
  1494. extradata += 5;
  1495. *pp += 4;
  1496. }
  1497. language[i * 4 - 1] = 0;
  1498. av_dict_set(&st->metadata, "language", language, 0);
  1499. }
  1500. }
  1501. break;
  1502. case 0x0a: /* ISO 639 language descriptor */
  1503. for (i = 0; i + 4 <= desc_len; i += 4) {
  1504. language[i + 0] = get8(pp, desc_end);
  1505. language[i + 1] = get8(pp, desc_end);
  1506. language[i + 2] = get8(pp, desc_end);
  1507. language[i + 3] = ',';
  1508. switch (get8(pp, desc_end)) {
  1509. case 0x01:
  1510. st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
  1511. break;
  1512. case 0x02:
  1513. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1514. break;
  1515. case 0x03:
  1516. st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  1517. break;
  1518. }
  1519. }
  1520. if (i && language[0]) {
  1521. language[i - 1] = 0;
  1522. av_dict_set(&st->metadata, "language", language, 0);
  1523. }
  1524. break;
  1525. case 0x05: /* registration descriptor */
  1526. st->codec->codec_tag = bytestream_get_le32(pp);
  1527. av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
  1528. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1529. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1530. break;
  1531. case 0x52: /* stream identifier descriptor */
  1532. st->stream_identifier = 1 + get8(pp, desc_end);
  1533. break;
  1534. case 0x26: /* metadata descriptor */
  1535. if (get16(pp, desc_end) == 0xFFFF)
  1536. *pp += 4;
  1537. if (get8(pp, desc_end) == 0xFF) {
  1538. st->codec->codec_tag = bytestream_get_le32(pp);
  1539. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1540. mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
  1541. }
  1542. break;
  1543. case 0x7f: /* DVB extension descriptor */
  1544. ext_desc_tag = get8(pp, desc_end);
  1545. if (ext_desc_tag < 0)
  1546. return AVERROR_INVALIDDATA;
  1547. if (st->codec->codec_id == AV_CODEC_ID_OPUS &&
  1548. ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
  1549. if (!st->codec->extradata) {
  1550. st->codec->extradata = av_mallocz(sizeof(opus_default_extradata) +
  1551. FF_INPUT_BUFFER_PADDING_SIZE);
  1552. if (!st->codec->extradata)
  1553. return AVERROR(ENOMEM);
  1554. st->codec->extradata_size = sizeof(opus_default_extradata);
  1555. memcpy(st->codec->extradata, opus_default_extradata, sizeof(opus_default_extradata));
  1556. channel_config_code = get8(pp, desc_end);
  1557. if (channel_config_code < 0)
  1558. return AVERROR_INVALIDDATA;
  1559. if (channel_config_code <= 0x8) {
  1560. st->codec->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
  1561. st->codec->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
  1562. st->codec->extradata[19] = opus_stream_cnt[channel_config_code];
  1563. st->codec->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
  1564. memcpy(&st->codec->extradata[21], opus_channel_map[channels - 1], channels);
  1565. } else {
  1566. avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
  1567. }
  1568. st->need_parsing = AVSTREAM_PARSE_FULL;
  1569. }
  1570. }
  1571. break;
  1572. default:
  1573. break;
  1574. }
  1575. *pp = desc_end;
  1576. return 0;
  1577. }
  1578. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1579. {
  1580. MpegTSContext *ts = filter->u.section_filter.opaque;
  1581. SectionHeader h1, *h = &h1;
  1582. PESContext *pes;
  1583. AVStream *st;
  1584. const uint8_t *p, *p_end, *desc_list_end;
  1585. int program_info_length, pcr_pid, pid, stream_type;
  1586. int desc_list_len;
  1587. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1588. int mp4_descr_count = 0;
  1589. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
  1590. int i;
  1591. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1592. hex_dump_debug(ts->stream, section, section_len);
  1593. p_end = section + section_len - 4;
  1594. p = section;
  1595. if (parse_section_header(h, &p, p_end) < 0)
  1596. return;
  1597. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d version=%d\n",
  1598. h->id, h->sec_num, h->last_sec_num, h->version);
  1599. if (h->tid != PMT_TID)
  1600. return;
  1601. if (!ts->scan_all_pmts && ts->skip_changes)
  1602. return;
  1603. if (!ts->skip_clear)
  1604. clear_program(ts, h->id);
  1605. pcr_pid = get16(&p, p_end);
  1606. if (pcr_pid < 0)
  1607. return;
  1608. pcr_pid &= 0x1fff;
  1609. add_pid_to_pmt(ts, h->id, pcr_pid);
  1610. set_pcr_pid(ts->stream, h->id, pcr_pid);
  1611. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1612. program_info_length = get16(&p, p_end);
  1613. if (program_info_length < 0)
  1614. return;
  1615. program_info_length &= 0xfff;
  1616. while (program_info_length >= 2) {
  1617. uint8_t tag, len;
  1618. tag = get8(&p, p_end);
  1619. len = get8(&p, p_end);
  1620. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1621. if (len > program_info_length - 2)
  1622. // something else is broken, exit the program_descriptors_loop
  1623. break;
  1624. program_info_length -= len + 2;
  1625. if (tag == 0x1d) { // IOD descriptor
  1626. get8(&p, p_end); // scope
  1627. get8(&p, p_end); // label
  1628. len -= 2;
  1629. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1630. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1631. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1632. prog_reg_desc = bytestream_get_le32(&p);
  1633. len -= 4;
  1634. }
  1635. p += len;
  1636. }
  1637. p += program_info_length;
  1638. if (p >= p_end)
  1639. goto out;
  1640. // stop parsing after pmt, we found header
  1641. if (!ts->stream->nb_streams)
  1642. ts->stop_parse = 2;
  1643. set_pmt_found(ts, h->id);
  1644. for (;;) {
  1645. st = 0;
  1646. pes = NULL;
  1647. stream_type = get8(&p, p_end);
  1648. if (stream_type < 0)
  1649. break;
  1650. pid = get16(&p, p_end);
  1651. if (pid < 0)
  1652. goto out;
  1653. pid &= 0x1fff;
  1654. if (pid == ts->current_pid)
  1655. goto out;
  1656. /* now create stream */
  1657. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1658. pes = ts->pids[pid]->u.pes_filter.opaque;
  1659. if (!pes->st) {
  1660. pes->st = avformat_new_stream(pes->stream, NULL);
  1661. if (!pes->st)
  1662. goto out;
  1663. pes->st->id = pes->pid;
  1664. }
  1665. st = pes->st;
  1666. } else if (stream_type != 0x13) {
  1667. if (ts->pids[pid])
  1668. mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
  1669. pes = add_pes_stream(ts, pid, pcr_pid);
  1670. if (pes) {
  1671. st = avformat_new_stream(pes->stream, NULL);
  1672. if (!st)
  1673. goto out;
  1674. st->id = pes->pid;
  1675. }
  1676. } else {
  1677. int idx = ff_find_stream_index(ts->stream, pid);
  1678. if (idx >= 0) {
  1679. st = ts->stream->streams[idx];
  1680. } else {
  1681. st = avformat_new_stream(ts->stream, NULL);
  1682. if (!st)
  1683. goto out;
  1684. st->id = pid;
  1685. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1686. }
  1687. }
  1688. if (!st)
  1689. goto out;
  1690. if (pes && !pes->stream_type)
  1691. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1692. add_pid_to_pmt(ts, h->id, pid);
  1693. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1694. desc_list_len = get16(&p, p_end);
  1695. if (desc_list_len < 0)
  1696. goto out;
  1697. desc_list_len &= 0xfff;
  1698. desc_list_end = p + desc_list_len;
  1699. if (desc_list_end > p_end)
  1700. goto out;
  1701. for (;;) {
  1702. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
  1703. desc_list_end, mp4_descr,
  1704. mp4_descr_count, pid, ts) < 0)
  1705. break;
  1706. if (pes && prog_reg_desc == AV_RL32("HDMV") &&
  1707. stream_type == 0x83 && pes->sub_st) {
  1708. ff_program_add_stream_index(ts->stream, h->id,
  1709. pes->sub_st->index);
  1710. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1711. }
  1712. }
  1713. p = desc_list_end;
  1714. }
  1715. if (!ts->pids[pcr_pid])
  1716. mpegts_open_pcr_filter(ts, pcr_pid);
  1717. out:
  1718. for (i = 0; i < mp4_descr_count; i++)
  1719. av_free(mp4_descr[i].dec_config_descr);
  1720. }
  1721. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1722. {
  1723. MpegTSContext *ts = filter->u.section_filter.opaque;
  1724. SectionHeader h1, *h = &h1;
  1725. const uint8_t *p, *p_end;
  1726. int sid, pmt_pid;
  1727. AVProgram *program;
  1728. av_dlog(ts->stream, "PAT:\n");
  1729. hex_dump_debug(ts->stream, section, section_len);
  1730. p_end = section + section_len - 4;
  1731. p = section;
  1732. if (parse_section_header(h, &p, p_end) < 0)
  1733. return;
  1734. if (h->tid != PAT_TID)
  1735. return;
  1736. if (ts->skip_changes)
  1737. return;
  1738. ts->stream->ts_id = h->id;
  1739. clear_programs(ts);
  1740. for (;;) {
  1741. sid = get16(&p, p_end);
  1742. if (sid < 0)
  1743. break;
  1744. pmt_pid = get16(&p, p_end);
  1745. if (pmt_pid < 0)
  1746. break;
  1747. pmt_pid &= 0x1fff;
  1748. if (pmt_pid == ts->current_pid)
  1749. break;
  1750. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1751. if (sid == 0x0000) {
  1752. /* NIT info */
  1753. } else {
  1754. MpegTSFilter *fil = ts->pids[pmt_pid];
  1755. program = av_new_program(ts->stream, sid);
  1756. if (program) {
  1757. program->program_num = sid;
  1758. program->pmt_pid = pmt_pid;
  1759. }
  1760. if (fil)
  1761. if ( fil->type != MPEGTS_SECTION
  1762. || fil->pid != pmt_pid
  1763. || fil->u.section_filter.section_cb != pmt_cb)
  1764. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1765. if (!ts->pids[pmt_pid])
  1766. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1767. add_pat_entry(ts, sid);
  1768. add_pid_to_pmt(ts, sid, 0); // add pat pid to program
  1769. add_pid_to_pmt(ts, sid, pmt_pid);
  1770. }
  1771. }
  1772. if (sid < 0) {
  1773. int i,j;
  1774. for (j=0; j<ts->stream->nb_programs; j++) {
  1775. for (i = 0; i < ts->nb_prg; i++)
  1776. if (ts->prg[i].id == ts->stream->programs[j]->id)
  1777. break;
  1778. if (i==ts->nb_prg && !ts->skip_clear)
  1779. clear_avprogram(ts, ts->stream->programs[j]->id);
  1780. }
  1781. }
  1782. }
  1783. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1784. {
  1785. MpegTSContext *ts = filter->u.section_filter.opaque;
  1786. SectionHeader h1, *h = &h1;
  1787. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1788. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1789. char *name, *provider_name;
  1790. av_dlog(ts->stream, "SDT:\n");
  1791. hex_dump_debug(ts->stream, section, section_len);
  1792. p_end = section + section_len - 4;
  1793. p = section;
  1794. if (parse_section_header(h, &p, p_end) < 0)
  1795. return;
  1796. if (h->tid != SDT_TID)
  1797. return;
  1798. if (ts->skip_changes)
  1799. return;
  1800. onid = get16(&p, p_end);
  1801. if (onid < 0)
  1802. return;
  1803. val = get8(&p, p_end);
  1804. if (val < 0)
  1805. return;
  1806. for (;;) {
  1807. sid = get16(&p, p_end);
  1808. if (sid < 0)
  1809. break;
  1810. val = get8(&p, p_end);
  1811. if (val < 0)
  1812. break;
  1813. desc_list_len = get16(&p, p_end);
  1814. if (desc_list_len < 0)
  1815. break;
  1816. desc_list_len &= 0xfff;
  1817. desc_list_end = p + desc_list_len;
  1818. if (desc_list_end > p_end)
  1819. break;
  1820. for (;;) {
  1821. desc_tag = get8(&p, desc_list_end);
  1822. if (desc_tag < 0)
  1823. break;
  1824. desc_len = get8(&p, desc_list_end);
  1825. desc_end = p + desc_len;
  1826. if (desc_len < 0 || desc_end > desc_list_end)
  1827. break;
  1828. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1829. desc_tag, desc_len);
  1830. switch (desc_tag) {
  1831. case 0x48:
  1832. service_type = get8(&p, p_end);
  1833. if (service_type < 0)
  1834. break;
  1835. provider_name = getstr8(&p, p_end);
  1836. if (!provider_name)
  1837. break;
  1838. name = getstr8(&p, p_end);
  1839. if (name) {
  1840. AVProgram *program = av_new_program(ts->stream, sid);
  1841. if (program) {
  1842. av_dict_set(&program->metadata, "service_name", name, 0);
  1843. av_dict_set(&program->metadata, "service_provider",
  1844. provider_name, 0);
  1845. }
  1846. }
  1847. av_free(name);
  1848. av_free(provider_name);
  1849. break;
  1850. default:
  1851. break;
  1852. }
  1853. p = desc_end;
  1854. }
  1855. p = desc_list_end;
  1856. }
  1857. }
  1858. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1859. const uint8_t *packet);
  1860. /* handle one TS packet */
  1861. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1862. {
  1863. MpegTSFilter *tss;
  1864. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1865. has_adaptation, has_payload;
  1866. const uint8_t *p, *p_end;
  1867. int64_t pos;
  1868. pid = AV_RB16(packet + 1) & 0x1fff;
  1869. if (pid && discard_pid(ts, pid))
  1870. return 0;
  1871. is_start = packet[1] & 0x40;
  1872. tss = ts->pids[pid];
  1873. if (ts->auto_guess && !tss && is_start) {
  1874. add_pes_stream(ts, pid, -1);
  1875. tss = ts->pids[pid];
  1876. }
  1877. if (!tss)
  1878. return 0;
  1879. ts->current_pid = pid;
  1880. afc = (packet[3] >> 4) & 3;
  1881. if (afc == 0) /* reserved value */
  1882. return 0;
  1883. has_adaptation = afc & 2;
  1884. has_payload = afc & 1;
  1885. is_discontinuity = has_adaptation &&
  1886. packet[4] != 0 && /* with length > 0 */
  1887. (packet[5] & 0x80); /* and discontinuity indicated */
  1888. /* continuity check (currently not used) */
  1889. cc = (packet[3] & 0xf);
  1890. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1891. cc_ok = pid == 0x1FFF || // null packet PID
  1892. is_discontinuity ||
  1893. tss->last_cc < 0 ||
  1894. expected_cc == cc;
  1895. tss->last_cc = cc;
  1896. if (!cc_ok) {
  1897. av_log(ts->stream, AV_LOG_DEBUG,
  1898. "Continuity check failed for pid %d expected %d got %d\n",
  1899. pid, expected_cc, cc);
  1900. if (tss->type == MPEGTS_PES) {
  1901. PESContext *pc = tss->u.pes_filter.opaque;
  1902. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1903. }
  1904. }
  1905. p = packet + 4;
  1906. if (has_adaptation) {
  1907. int64_t pcr_h;
  1908. int pcr_l;
  1909. if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
  1910. tss->last_pcr = pcr_h * 300 + pcr_l;
  1911. /* skip adaptation field */
  1912. p += p[0] + 1;
  1913. }
  1914. /* if past the end of packet, ignore */
  1915. p_end = packet + TS_PACKET_SIZE;
  1916. if (p >= p_end || !has_payload)
  1917. return 0;
  1918. pos = avio_tell(ts->stream->pb);
  1919. if (pos >= 0) {
  1920. av_assert0(pos >= TS_PACKET_SIZE);
  1921. ts->pos47_full = pos - TS_PACKET_SIZE;
  1922. }
  1923. if (tss->type == MPEGTS_SECTION) {
  1924. if (is_start) {
  1925. /* pointer field present */
  1926. len = *p++;
  1927. if (p + len > p_end)
  1928. return 0;
  1929. if (len && cc_ok) {
  1930. /* write remaining section bytes */
  1931. write_section_data(ts, tss,
  1932. p, len, 0);
  1933. /* check whether filter has been closed */
  1934. if (!ts->pids[pid])
  1935. return 0;
  1936. }
  1937. p += len;
  1938. if (p < p_end) {
  1939. write_section_data(ts, tss,
  1940. p, p_end - p, 1);
  1941. }
  1942. } else {
  1943. if (cc_ok) {
  1944. write_section_data(ts, tss,
  1945. p, p_end - p, 0);
  1946. }
  1947. }
  1948. // stop find_stream_info from waiting for more streams
  1949. // when all programs have received a PMT
  1950. if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
  1951. int i;
  1952. for (i = 0; i < ts->nb_prg; i++) {
  1953. if (!ts->prg[i].pmt_found)
  1954. break;
  1955. }
  1956. if (i == ts->nb_prg && ts->nb_prg > 0) {
  1957. int types = 0;
  1958. for (i = 0; i < ts->stream->nb_streams; i++) {
  1959. AVStream *st = ts->stream->streams[i];
  1960. types |= 1<<st->codec->codec_type;
  1961. }
  1962. if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
  1963. av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
  1964. ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1965. }
  1966. }
  1967. }
  1968. } else {
  1969. int ret;
  1970. // Note: The position here points actually behind the current packet.
  1971. if (tss->type == MPEGTS_PES) {
  1972. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1973. pos - ts->raw_packet_size)) < 0)
  1974. return ret;
  1975. }
  1976. }
  1977. return 0;
  1978. }
  1979. static void reanalyze(MpegTSContext *ts) {
  1980. AVIOContext *pb = ts->stream->pb;
  1981. int64_t pos = avio_tell(pb);
  1982. if (pos < 0)
  1983. return;
  1984. pos -= ts->pos47_full;
  1985. if (pos == TS_PACKET_SIZE) {
  1986. ts->size_stat[0] ++;
  1987. } else if (pos == TS_DVHS_PACKET_SIZE) {
  1988. ts->size_stat[1] ++;
  1989. } else if (pos == TS_FEC_PACKET_SIZE) {
  1990. ts->size_stat[2] ++;
  1991. }
  1992. ts->size_stat_count ++;
  1993. if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
  1994. int newsize = 0;
  1995. if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
  1996. newsize = TS_PACKET_SIZE;
  1997. } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
  1998. newsize = TS_DVHS_PACKET_SIZE;
  1999. } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
  2000. newsize = TS_FEC_PACKET_SIZE;
  2001. }
  2002. if (newsize && newsize != ts->raw_packet_size) {
  2003. av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
  2004. ts->raw_packet_size = newsize;
  2005. }
  2006. ts->size_stat_count = 0;
  2007. memset(ts->size_stat, 0, sizeof(ts->size_stat));
  2008. }
  2009. }
  2010. /* XXX: try to find a better synchro over several packets (use
  2011. * get_packet_size() ?) */
  2012. static int mpegts_resync(AVFormatContext *s)
  2013. {
  2014. MpegTSContext *ts = s->priv_data;
  2015. AVIOContext *pb = s->pb;
  2016. int c, i;
  2017. for (i = 0; i < ts->resync_size; i++) {
  2018. c = avio_r8(pb);
  2019. if (avio_feof(pb))
  2020. return AVERROR_EOF;
  2021. if (c == 0x47) {
  2022. avio_seek(pb, -1, SEEK_CUR);
  2023. reanalyze(s->priv_data);
  2024. return 0;
  2025. }
  2026. }
  2027. av_log(s, AV_LOG_ERROR,
  2028. "max resync size reached, could not find sync byte\n");
  2029. /* no sync found */
  2030. return AVERROR_INVALIDDATA;
  2031. }
  2032. /* return AVERROR_something if error or EOF. Return 0 if OK. */
  2033. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
  2034. const uint8_t **data)
  2035. {
  2036. AVIOContext *pb = s->pb;
  2037. int len;
  2038. for (;;) {
  2039. len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
  2040. if (len != TS_PACKET_SIZE)
  2041. return len < 0 ? len : AVERROR_EOF;
  2042. /* check packet sync byte */
  2043. if ((*data)[0] != 0x47) {
  2044. /* find a new packet start */
  2045. uint64_t pos = avio_tell(pb);
  2046. avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
  2047. if (mpegts_resync(s) < 0)
  2048. return AVERROR(EAGAIN);
  2049. else
  2050. continue;
  2051. } else {
  2052. break;
  2053. }
  2054. }
  2055. return 0;
  2056. }
  2057. static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
  2058. {
  2059. AVIOContext *pb = s->pb;
  2060. int skip = raw_packet_size - TS_PACKET_SIZE;
  2061. if (skip > 0)
  2062. avio_skip(pb, skip);
  2063. }
  2064. static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
  2065. {
  2066. AVFormatContext *s = ts->stream;
  2067. uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  2068. const uint8_t *data;
  2069. int64_t packet_num;
  2070. int ret = 0;
  2071. if (avio_tell(s->pb) != ts->last_pos) {
  2072. int i;
  2073. av_dlog(ts->stream, "Skipping after seek\n");
  2074. /* seek detected, flush pes buffer */
  2075. for (i = 0; i < NB_PID_MAX; i++) {
  2076. if (ts->pids[i]) {
  2077. if (ts->pids[i]->type == MPEGTS_PES) {
  2078. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2079. av_buffer_unref(&pes->buffer);
  2080. pes->data_index = 0;
  2081. pes->state = MPEGTS_SKIP; /* skip until pes header */
  2082. }
  2083. ts->pids[i]->last_cc = -1;
  2084. ts->pids[i]->last_pcr = -1;
  2085. }
  2086. }
  2087. }
  2088. ts->stop_parse = 0;
  2089. packet_num = 0;
  2090. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2091. for (;;) {
  2092. packet_num++;
  2093. if (nb_packets != 0 && packet_num >= nb_packets ||
  2094. ts->stop_parse > 1) {
  2095. ret = AVERROR(EAGAIN);
  2096. break;
  2097. }
  2098. if (ts->stop_parse > 0)
  2099. break;
  2100. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2101. if (ret != 0)
  2102. break;
  2103. ret = handle_packet(ts, data);
  2104. finished_reading_packet(s, ts->raw_packet_size);
  2105. if (ret != 0)
  2106. break;
  2107. }
  2108. ts->last_pos = avio_tell(s->pb);
  2109. return ret;
  2110. }
  2111. static int mpegts_probe(AVProbeData *p)
  2112. {
  2113. const int size = p->buf_size;
  2114. int maxscore = 0;
  2115. int sumscore = 0;
  2116. int i;
  2117. int check_count = size / TS_FEC_PACKET_SIZE;
  2118. #define CHECK_COUNT 10
  2119. #define CHECK_BLOCK 100
  2120. if (check_count < CHECK_COUNT)
  2121. return AVERROR_INVALIDDATA;
  2122. for (i = 0; i<check_count; i+=CHECK_BLOCK) {
  2123. int left = FFMIN(check_count - i, CHECK_BLOCK);
  2124. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
  2125. int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  2126. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  2127. score = FFMAX3(score, dvhs_score, fec_score);
  2128. sumscore += score;
  2129. maxscore = FFMAX(maxscore, score);
  2130. }
  2131. sumscore = sumscore * CHECK_COUNT / check_count;
  2132. maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
  2133. av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  2134. if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  2135. else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  2136. else
  2137. return AVERROR_INVALIDDATA;
  2138. }
  2139. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  2140. * (-1) if not available */
  2141. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
  2142. {
  2143. int afc, len, flags;
  2144. const uint8_t *p;
  2145. unsigned int v;
  2146. afc = (packet[3] >> 4) & 3;
  2147. if (afc <= 1)
  2148. return AVERROR_INVALIDDATA;
  2149. p = packet + 4;
  2150. len = p[0];
  2151. p++;
  2152. if (len == 0)
  2153. return AVERROR_INVALIDDATA;
  2154. flags = *p++;
  2155. len--;
  2156. if (!(flags & 0x10))
  2157. return AVERROR_INVALIDDATA;
  2158. if (len < 6)
  2159. return AVERROR_INVALIDDATA;
  2160. v = AV_RB32(p);
  2161. *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
  2162. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  2163. return 0;
  2164. }
  2165. static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
  2166. /* NOTE: We attempt to seek on non-seekable files as well, as the
  2167. * probe buffer usually is big enough. Only warn if the seek failed
  2168. * on files where the seek should work. */
  2169. if (avio_seek(pb, pos, SEEK_SET) < 0)
  2170. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  2171. }
  2172. static int mpegts_read_header(AVFormatContext *s)
  2173. {
  2174. MpegTSContext *ts = s->priv_data;
  2175. AVIOContext *pb = s->pb;
  2176. uint8_t buf[8 * 1024] = {0};
  2177. int len;
  2178. int64_t pos, probesize = s->probesize ? s->probesize : s->probesize2;
  2179. if (ffio_ensure_seekback(pb, probesize) < 0)
  2180. av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
  2181. /* read the first 8192 bytes to get packet size */
  2182. pos = avio_tell(pb);
  2183. len = avio_read(pb, buf, sizeof(buf));
  2184. ts->raw_packet_size = get_packet_size(buf, len);
  2185. if (ts->raw_packet_size <= 0) {
  2186. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  2187. ts->raw_packet_size = TS_PACKET_SIZE;
  2188. }
  2189. ts->stream = s;
  2190. ts->auto_guess = 0;
  2191. if (s->iformat == &ff_mpegts_demuxer) {
  2192. /* normal demux */
  2193. /* first do a scan to get all the services */
  2194. seek_back(s, pb, pos);
  2195. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2196. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2197. handle_packets(ts, probesize / ts->raw_packet_size);
  2198. /* if could not find service, enable auto_guess */
  2199. ts->auto_guess = 1;
  2200. av_dlog(ts->stream, "tuning done\n");
  2201. s->ctx_flags |= AVFMTCTX_NOHEADER;
  2202. } else {
  2203. AVStream *st;
  2204. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  2205. int64_t pcrs[2], pcr_h;
  2206. int packet_count[2];
  2207. uint8_t packet[TS_PACKET_SIZE];
  2208. const uint8_t *data;
  2209. /* only read packets */
  2210. st = avformat_new_stream(s, NULL);
  2211. if (!st)
  2212. return AVERROR(ENOMEM);
  2213. avpriv_set_pts_info(st, 60, 1, 27000000);
  2214. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2215. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  2216. /* we iterate until we find two PCRs to estimate the bitrate */
  2217. pcr_pid = -1;
  2218. nb_pcrs = 0;
  2219. nb_packets = 0;
  2220. for (;;) {
  2221. ret = read_packet(s, packet, ts->raw_packet_size, &data);
  2222. if (ret < 0)
  2223. return ret;
  2224. pid = AV_RB16(data + 1) & 0x1fff;
  2225. if ((pcr_pid == -1 || pcr_pid == pid) &&
  2226. parse_pcr(&pcr_h, &pcr_l, data) == 0) {
  2227. finished_reading_packet(s, ts->raw_packet_size);
  2228. pcr_pid = pid;
  2229. packet_count[nb_pcrs] = nb_packets;
  2230. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  2231. nb_pcrs++;
  2232. if (nb_pcrs >= 2)
  2233. break;
  2234. } else {
  2235. finished_reading_packet(s, ts->raw_packet_size);
  2236. }
  2237. nb_packets++;
  2238. }
  2239. /* NOTE1: the bitrate is computed without the FEC */
  2240. /* NOTE2: it is only the bitrate of the start of the stream */
  2241. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  2242. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  2243. s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
  2244. st->codec->bit_rate = s->bit_rate;
  2245. st->start_time = ts->cur_pcr;
  2246. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  2247. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  2248. }
  2249. seek_back(s, pb, pos);
  2250. return 0;
  2251. }
  2252. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  2253. static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
  2254. {
  2255. MpegTSContext *ts = s->priv_data;
  2256. int ret, i;
  2257. int64_t pcr_h, next_pcr_h, pos;
  2258. int pcr_l, next_pcr_l;
  2259. uint8_t pcr_buf[12];
  2260. const uint8_t *data;
  2261. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  2262. return AVERROR(ENOMEM);
  2263. ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
  2264. pkt->pos = avio_tell(s->pb);
  2265. if (ret < 0) {
  2266. av_free_packet(pkt);
  2267. return ret;
  2268. }
  2269. if (data != pkt->data)
  2270. memcpy(pkt->data, data, ts->raw_packet_size);
  2271. finished_reading_packet(s, ts->raw_packet_size);
  2272. if (ts->mpeg2ts_compute_pcr) {
  2273. /* compute exact PCR for each packet */
  2274. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  2275. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  2276. pos = avio_tell(s->pb);
  2277. for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
  2278. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  2279. avio_read(s->pb, pcr_buf, 12);
  2280. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  2281. /* XXX: not precise enough */
  2282. ts->pcr_incr =
  2283. ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  2284. (i + 1);
  2285. break;
  2286. }
  2287. }
  2288. avio_seek(s->pb, pos, SEEK_SET);
  2289. /* no next PCR found: we use previous increment */
  2290. ts->cur_pcr = pcr_h * 300 + pcr_l;
  2291. }
  2292. pkt->pts = ts->cur_pcr;
  2293. pkt->duration = ts->pcr_incr;
  2294. ts->cur_pcr += ts->pcr_incr;
  2295. }
  2296. pkt->stream_index = 0;
  2297. return 0;
  2298. }
  2299. static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
  2300. {
  2301. MpegTSContext *ts = s->priv_data;
  2302. int ret, i;
  2303. pkt->size = -1;
  2304. ts->pkt = pkt;
  2305. ret = handle_packets(ts, 0);
  2306. if (ret < 0) {
  2307. av_free_packet(ts->pkt);
  2308. /* flush pes data left */
  2309. for (i = 0; i < NB_PID_MAX; i++)
  2310. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  2311. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  2312. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  2313. new_pes_packet(pes, pkt);
  2314. pes->state = MPEGTS_SKIP;
  2315. ret = 0;
  2316. break;
  2317. }
  2318. }
  2319. }
  2320. if (!ret && pkt->size < 0)
  2321. ret = AVERROR(EINTR);
  2322. return ret;
  2323. }
  2324. static void mpegts_free(MpegTSContext *ts)
  2325. {
  2326. int i;
  2327. clear_programs(ts);
  2328. for (i = 0; i < NB_PID_MAX; i++)
  2329. if (ts->pids[i])
  2330. mpegts_close_filter(ts, ts->pids[i]);
  2331. }
  2332. static int mpegts_read_close(AVFormatContext *s)
  2333. {
  2334. MpegTSContext *ts = s->priv_data;
  2335. mpegts_free(ts);
  2336. return 0;
  2337. }
  2338. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  2339. int64_t *ppos, int64_t pos_limit)
  2340. {
  2341. MpegTSContext *ts = s->priv_data;
  2342. int64_t pos, timestamp;
  2343. uint8_t buf[TS_PACKET_SIZE];
  2344. int pcr_l, pcr_pid =
  2345. ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
  2346. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2347. pos =
  2348. ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
  2349. ts->raw_packet_size + pos47;
  2350. while(pos < pos_limit) {
  2351. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2352. return AV_NOPTS_VALUE;
  2353. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  2354. return AV_NOPTS_VALUE;
  2355. if (buf[0] != 0x47) {
  2356. avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
  2357. if (mpegts_resync(s) < 0)
  2358. return AV_NOPTS_VALUE;
  2359. pos = avio_tell(s->pb);
  2360. continue;
  2361. }
  2362. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  2363. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  2364. *ppos = pos;
  2365. return timestamp;
  2366. }
  2367. pos += ts->raw_packet_size;
  2368. }
  2369. return AV_NOPTS_VALUE;
  2370. }
  2371. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  2372. int64_t *ppos, int64_t pos_limit)
  2373. {
  2374. MpegTSContext *ts = s->priv_data;
  2375. int64_t pos;
  2376. int pos47 = ts->pos47_full % ts->raw_packet_size;
  2377. pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
  2378. ff_read_frame_flush(s);
  2379. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  2380. return AV_NOPTS_VALUE;
  2381. while(pos < pos_limit) {
  2382. int ret;
  2383. AVPacket pkt;
  2384. av_init_packet(&pkt);
  2385. ret = av_read_frame(s, &pkt);
  2386. if (ret < 0)
  2387. return AV_NOPTS_VALUE;
  2388. av_free_packet(&pkt);
  2389. if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
  2390. ff_reduce_index(s, pkt.stream_index);
  2391. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  2392. if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
  2393. *ppos = pkt.pos;
  2394. return pkt.dts;
  2395. }
  2396. }
  2397. pos = pkt.pos;
  2398. }
  2399. return AV_NOPTS_VALUE;
  2400. }
  2401. /**************************************************************/
  2402. /* parsing functions - called from other demuxers such as RTP */
  2403. MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
  2404. {
  2405. MpegTSContext *ts;
  2406. ts = av_mallocz(sizeof(MpegTSContext));
  2407. if (!ts)
  2408. return NULL;
  2409. /* no stream case, currently used by RTP */
  2410. ts->raw_packet_size = TS_PACKET_SIZE;
  2411. ts->stream = s;
  2412. ts->auto_guess = 1;
  2413. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  2414. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2415. return ts;
  2416. }
  2417. /* return the consumed length if a packet was output, or -1 if no
  2418. * packet is output */
  2419. int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2420. const uint8_t *buf, int len)
  2421. {
  2422. int len1;
  2423. len1 = len;
  2424. ts->pkt = pkt;
  2425. for (;;) {
  2426. ts->stop_parse = 0;
  2427. if (len < TS_PACKET_SIZE)
  2428. return AVERROR_INVALIDDATA;
  2429. if (buf[0] != 0x47) {
  2430. buf++;
  2431. len--;
  2432. } else {
  2433. handle_packet(ts, buf);
  2434. buf += TS_PACKET_SIZE;
  2435. len -= TS_PACKET_SIZE;
  2436. if (ts->stop_parse == 1)
  2437. break;
  2438. }
  2439. }
  2440. return len1 - len;
  2441. }
  2442. void avpriv_mpegts_parse_close(MpegTSContext *ts)
  2443. {
  2444. mpegts_free(ts);
  2445. av_free(ts);
  2446. }
  2447. AVInputFormat ff_mpegts_demuxer = {
  2448. .name = "mpegts",
  2449. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2450. .priv_data_size = sizeof(MpegTSContext),
  2451. .read_probe = mpegts_probe,
  2452. .read_header = mpegts_read_header,
  2453. .read_packet = mpegts_read_packet,
  2454. .read_close = mpegts_read_close,
  2455. .read_timestamp = mpegts_get_dts,
  2456. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2457. .priv_class = &mpegts_class,
  2458. };
  2459. AVInputFormat ff_mpegtsraw_demuxer = {
  2460. .name = "mpegtsraw",
  2461. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2462. .priv_data_size = sizeof(MpegTSContext),
  2463. .read_header = mpegts_read_header,
  2464. .read_packet = mpegts_raw_read_packet,
  2465. .read_close = mpegts_read_close,
  2466. .read_timestamp = mpegts_get_dts,
  2467. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2468. .priv_class = &mpegtsraw_class,
  2469. };