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.

2768 lines
90KB

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