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.

2791 lines
92KB

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