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.

2198 lines
69KB

  1. /*
  2. * MPEG2 transport stream (aka DVB) demuxer
  3. * Copyright (c) 2002-2003 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/crc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/log.h"
  24. #include "libavutil/dict.h"
  25. #include "libavutil/mathematics.h"
  26. #include "libavutil/opt.h"
  27. #include "libavcodec/bytestream.h"
  28. #include "libavcodec/get_bits.h"
  29. #include "avformat.h"
  30. #include "mpegts.h"
  31. #include "internal.h"
  32. #include "avio_internal.h"
  33. #include "seek.h"
  34. #include "mpeg.h"
  35. #include "isom.h"
  36. /* maximum size in which we look for synchronisation if
  37. synchronisation is lost */
  38. #define MAX_RESYNC_SIZE 65536
  39. #define MAX_PES_PAYLOAD 200*1024
  40. #define MAX_MP4_DESCR_COUNT 16
  41. enum MpegTSFilterType {
  42. MPEGTS_PES,
  43. MPEGTS_SECTION,
  44. };
  45. typedef struct MpegTSFilter MpegTSFilter;
  46. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
  47. typedef struct MpegTSPESFilter {
  48. PESCallback *pes_cb;
  49. void *opaque;
  50. } MpegTSPESFilter;
  51. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  52. typedef void SetServiceCallback(void *opaque, int ret);
  53. typedef struct MpegTSSectionFilter {
  54. int section_index;
  55. int section_h_size;
  56. uint8_t *section_buf;
  57. unsigned int check_crc:1;
  58. unsigned int end_of_section_reached:1;
  59. SectionCallback *section_cb;
  60. void *opaque;
  61. } MpegTSSectionFilter;
  62. struct MpegTSFilter {
  63. int pid;
  64. int es_id;
  65. int last_cc; /* last cc code (-1 if first packet) */
  66. enum MpegTSFilterType type;
  67. union {
  68. MpegTSPESFilter pes_filter;
  69. MpegTSSectionFilter section_filter;
  70. } u;
  71. };
  72. #define MAX_PIDS_PER_PROGRAM 64
  73. struct Program {
  74. unsigned int id; //program id/service id
  75. unsigned int nb_pids;
  76. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  77. };
  78. struct MpegTSContext {
  79. const AVClass *class;
  80. /* user data */
  81. AVFormatContext *stream;
  82. /** raw packet size, including FEC if present */
  83. int raw_packet_size;
  84. int pos47;
  85. /** if true, all pids are analyzed to find streams */
  86. int auto_guess;
  87. /** compute exact PCR for each transport stream packet */
  88. int mpeg2ts_compute_pcr;
  89. int64_t cur_pcr; /**< used to estimate the exact PCR */
  90. int pcr_incr; /**< used to estimate the exact PCR */
  91. /* data needed to handle file based ts */
  92. /** stop parsing loop */
  93. int stop_parse;
  94. /** packet containing Audio/Video data */
  95. AVPacket *pkt;
  96. /** to detect seek */
  97. int64_t last_pos;
  98. /******************************************/
  99. /* private mpegts data */
  100. /* scan context */
  101. /** structure to keep track of Program->pids mapping */
  102. unsigned int nb_prg;
  103. struct Program *prg;
  104. /** filters for various streams specified by PMT + for the PAT and PMT */
  105. MpegTSFilter *pids[NB_PID_MAX];
  106. };
  107. static const AVOption options[] = {
  108. {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
  109. {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  110. { NULL },
  111. };
  112. static const AVClass mpegtsraw_class = {
  113. .class_name = "mpegtsraw demuxer",
  114. .item_name = av_default_item_name,
  115. .option = options,
  116. .version = LIBAVUTIL_VERSION_INT,
  117. };
  118. /* TS stream handling */
  119. enum MpegTSState {
  120. MPEGTS_HEADER = 0,
  121. MPEGTS_PESHEADER,
  122. MPEGTS_PESHEADER_FILL,
  123. MPEGTS_PAYLOAD,
  124. MPEGTS_SKIP,
  125. };
  126. /* enough for PES header + length */
  127. #define PES_START_SIZE 6
  128. #define PES_HEADER_SIZE 9
  129. #define MAX_PES_HEADER_SIZE (9 + 255)
  130. typedef struct PESContext {
  131. int pid;
  132. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  133. int stream_type;
  134. MpegTSContext *ts;
  135. AVFormatContext *stream;
  136. AVStream *st;
  137. AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  138. enum MpegTSState state;
  139. /* used to get the format */
  140. int data_index;
  141. int flags; /**< copied to the AVPacket flags */
  142. int total_size;
  143. int pes_header_size;
  144. int extended_stream_id;
  145. int64_t pts, dts;
  146. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  147. uint8_t header[MAX_PES_HEADER_SIZE];
  148. uint8_t *buffer;
  149. SLConfigDescr sl;
  150. } PESContext;
  151. extern AVInputFormat ff_mpegts_demuxer;
  152. static void clear_program(MpegTSContext *ts, unsigned int programid)
  153. {
  154. int i;
  155. for(i=0; i<ts->nb_prg; i++)
  156. if(ts->prg[i].id == programid)
  157. ts->prg[i].nb_pids = 0;
  158. }
  159. static void clear_programs(MpegTSContext *ts)
  160. {
  161. av_freep(&ts->prg);
  162. ts->nb_prg=0;
  163. }
  164. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  165. {
  166. struct Program *p;
  167. void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
  168. if(!tmp)
  169. return;
  170. ts->prg = tmp;
  171. p = &ts->prg[ts->nb_prg];
  172. p->id = programid;
  173. p->nb_pids = 0;
  174. ts->nb_prg++;
  175. }
  176. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  177. {
  178. int i;
  179. struct Program *p = NULL;
  180. for(i=0; i<ts->nb_prg; i++) {
  181. if(ts->prg[i].id == programid) {
  182. p = &ts->prg[i];
  183. break;
  184. }
  185. }
  186. if(!p)
  187. return;
  188. if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  189. return;
  190. p->pids[p->nb_pids++] = pid;
  191. }
  192. /**
  193. * @brief discard_pid() decides if the pid is to be discarded according
  194. * to caller's programs selection
  195. * @param ts : - TS context
  196. * @param pid : - pid
  197. * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  198. * 0 otherwise
  199. */
  200. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  201. {
  202. int i, j, k;
  203. int used = 0, discarded = 0;
  204. struct Program *p;
  205. for(i=0; i<ts->nb_prg; i++) {
  206. p = &ts->prg[i];
  207. for(j=0; j<p->nb_pids; j++) {
  208. if(p->pids[j] != pid)
  209. continue;
  210. //is program with id p->id set to be discarded?
  211. for(k=0; k<ts->stream->nb_programs; k++) {
  212. if(ts->stream->programs[k]->id == p->id) {
  213. if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  214. discarded++;
  215. else
  216. used++;
  217. }
  218. }
  219. }
  220. }
  221. return !used && discarded;
  222. }
  223. /**
  224. * Assemble PES packets out of TS packets, and then call the "section_cb"
  225. * function when they are complete.
  226. */
  227. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  228. const uint8_t *buf, int buf_size, int is_start)
  229. {
  230. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  231. int len;
  232. if (is_start) {
  233. memcpy(tss->section_buf, buf, buf_size);
  234. tss->section_index = buf_size;
  235. tss->section_h_size = -1;
  236. tss->end_of_section_reached = 0;
  237. } else {
  238. if (tss->end_of_section_reached)
  239. return;
  240. len = 4096 - tss->section_index;
  241. if (buf_size < len)
  242. len = buf_size;
  243. memcpy(tss->section_buf + tss->section_index, buf, len);
  244. tss->section_index += len;
  245. }
  246. /* compute section length if possible */
  247. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  248. len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  249. if (len > 4096)
  250. return;
  251. tss->section_h_size = len;
  252. }
  253. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  254. tss->end_of_section_reached = 1;
  255. if (!tss->check_crc ||
  256. av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
  257. tss->section_buf, tss->section_h_size) == 0)
  258. tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  259. }
  260. }
  261. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  262. SectionCallback *section_cb, void *opaque,
  263. int check_crc)
  264. {
  265. MpegTSFilter *filter;
  266. MpegTSSectionFilter *sec;
  267. av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
  268. if (pid >= NB_PID_MAX || ts->pids[pid])
  269. return NULL;
  270. filter = av_mallocz(sizeof(MpegTSFilter));
  271. if (!filter)
  272. return NULL;
  273. ts->pids[pid] = filter;
  274. filter->type = MPEGTS_SECTION;
  275. filter->pid = pid;
  276. filter->es_id = -1;
  277. filter->last_cc = -1;
  278. sec = &filter->u.section_filter;
  279. sec->section_cb = section_cb;
  280. sec->opaque = opaque;
  281. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  282. sec->check_crc = check_crc;
  283. if (!sec->section_buf) {
  284. av_free(filter);
  285. return NULL;
  286. }
  287. return filter;
  288. }
  289. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  290. PESCallback *pes_cb,
  291. void *opaque)
  292. {
  293. MpegTSFilter *filter;
  294. MpegTSPESFilter *pes;
  295. if (pid >= NB_PID_MAX || ts->pids[pid])
  296. return NULL;
  297. filter = av_mallocz(sizeof(MpegTSFilter));
  298. if (!filter)
  299. return NULL;
  300. ts->pids[pid] = filter;
  301. filter->type = MPEGTS_PES;
  302. filter->pid = pid;
  303. filter->es_id = -1;
  304. filter->last_cc = -1;
  305. pes = &filter->u.pes_filter;
  306. pes->pes_cb = pes_cb;
  307. pes->opaque = opaque;
  308. return filter;
  309. }
  310. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  311. {
  312. int pid;
  313. pid = filter->pid;
  314. if (filter->type == MPEGTS_SECTION)
  315. av_freep(&filter->u.section_filter.section_buf);
  316. else if (filter->type == MPEGTS_PES) {
  317. PESContext *pes = filter->u.pes_filter.opaque;
  318. av_freep(&pes->buffer);
  319. /* referenced private data will be freed later in
  320. * avformat_close_input */
  321. if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  322. av_freep(&filter->u.pes_filter.opaque);
  323. }
  324. }
  325. av_free(filter);
  326. ts->pids[pid] = NULL;
  327. }
  328. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  329. int stat[TS_MAX_PACKET_SIZE];
  330. int i;
  331. int x=0;
  332. int best_score=0;
  333. memset(stat, 0, packet_size*sizeof(int));
  334. for(x=i=0; i<size-3; i++){
  335. if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
  336. stat[x]++;
  337. if(stat[x] > best_score){
  338. best_score= stat[x];
  339. if(index) *index= x;
  340. }
  341. }
  342. x++;
  343. if(x == packet_size) x= 0;
  344. }
  345. return best_score;
  346. }
  347. /* autodetect fec presence. Must have at least 1024 bytes */
  348. static int get_packet_size(const uint8_t *buf, int size)
  349. {
  350. int score, fec_score, dvhs_score;
  351. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  352. return -1;
  353. score = analyze(buf, size, TS_PACKET_SIZE, NULL);
  354. dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  355. fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  356. av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  357. score, dvhs_score, fec_score);
  358. if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  359. else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  360. else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  361. else return -1;
  362. }
  363. typedef struct SectionHeader {
  364. uint8_t tid;
  365. uint16_t id;
  366. uint8_t version;
  367. uint8_t sec_num;
  368. uint8_t last_sec_num;
  369. } SectionHeader;
  370. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  371. {
  372. const uint8_t *p;
  373. int c;
  374. p = *pp;
  375. if (p >= p_end)
  376. return -1;
  377. c = *p++;
  378. *pp = p;
  379. return c;
  380. }
  381. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  382. {
  383. const uint8_t *p;
  384. int c;
  385. p = *pp;
  386. if ((p + 1) >= p_end)
  387. return -1;
  388. c = AV_RB16(p);
  389. p += 2;
  390. *pp = p;
  391. return c;
  392. }
  393. /* read and allocate a DVB string preceded by its length */
  394. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  395. {
  396. int len;
  397. const uint8_t *p;
  398. char *str;
  399. p = *pp;
  400. len = get8(&p, p_end);
  401. if (len < 0)
  402. return NULL;
  403. if ((p + len) > p_end)
  404. return NULL;
  405. str = av_malloc(len + 1);
  406. if (!str)
  407. return NULL;
  408. memcpy(str, p, len);
  409. str[len] = '\0';
  410. p += len;
  411. *pp = p;
  412. return str;
  413. }
  414. static int parse_section_header(SectionHeader *h,
  415. const uint8_t **pp, const uint8_t *p_end)
  416. {
  417. int val;
  418. val = get8(pp, p_end);
  419. if (val < 0)
  420. return -1;
  421. h->tid = val;
  422. *pp += 2;
  423. val = get16(pp, p_end);
  424. if (val < 0)
  425. return -1;
  426. h->id = val;
  427. val = get8(pp, p_end);
  428. if (val < 0)
  429. return -1;
  430. h->version = (val >> 1) & 0x1f;
  431. val = get8(pp, p_end);
  432. if (val < 0)
  433. return -1;
  434. h->sec_num = val;
  435. val = get8(pp, p_end);
  436. if (val < 0)
  437. return -1;
  438. h->last_sec_num = val;
  439. return 0;
  440. }
  441. typedef struct {
  442. uint32_t stream_type;
  443. enum AVMediaType codec_type;
  444. enum AVCodecID codec_id;
  445. } StreamType;
  446. static const StreamType ISO_types[] = {
  447. { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  448. { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  449. { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  450. { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  451. { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
  452. { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
  453. { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
  454. { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
  455. { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  456. { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  457. { 0 },
  458. };
  459. static const StreamType HDMV_types[] = {
  460. { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
  461. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  462. { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  463. { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
  464. { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  465. { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
  466. { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
  467. { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
  468. { 0 },
  469. };
  470. /* ATSC ? */
  471. static const StreamType MISC_types[] = {
  472. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  473. { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  474. { 0 },
  475. };
  476. static const StreamType REGD_types[] = {
  477. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  478. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  479. { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
  480. { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  481. { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  482. { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  483. { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  484. { 0 },
  485. };
  486. /* descriptor present */
  487. static const StreamType DESC_types[] = {
  488. { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
  489. { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  490. { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  491. { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
  492. { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  493. { 0 },
  494. };
  495. static void mpegts_find_stream_type(AVStream *st,
  496. uint32_t stream_type, const StreamType *types)
  497. {
  498. for (; types->stream_type; types++) {
  499. if (stream_type == types->stream_type) {
  500. st->codec->codec_type = types->codec_type;
  501. st->codec->codec_id = types->codec_id;
  502. return;
  503. }
  504. }
  505. }
  506. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  507. uint32_t stream_type, uint32_t prog_reg_desc)
  508. {
  509. avpriv_set_pts_info(st, 33, 1, 90000);
  510. st->priv_data = pes;
  511. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  512. st->codec->codec_id = AV_CODEC_ID_NONE;
  513. st->need_parsing = AVSTREAM_PARSE_FULL;
  514. pes->st = st;
  515. pes->stream_type = stream_type;
  516. av_log(pes->stream, AV_LOG_DEBUG,
  517. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  518. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  519. st->codec->codec_tag = pes->stream_type;
  520. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  521. if (prog_reg_desc == AV_RL32("HDMV") &&
  522. st->codec->codec_id == AV_CODEC_ID_NONE) {
  523. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  524. if (pes->stream_type == 0x83) {
  525. // HDMV TrueHD streams also contain an AC3 coded version of the
  526. // audio track - add a second stream for this
  527. AVStream *sub_st;
  528. // priv_data cannot be shared between streams
  529. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  530. if (!sub_pes)
  531. return AVERROR(ENOMEM);
  532. memcpy(sub_pes, pes, sizeof(*sub_pes));
  533. sub_st = avformat_new_stream(pes->stream, NULL);
  534. if (!sub_st) {
  535. av_free(sub_pes);
  536. return AVERROR(ENOMEM);
  537. }
  538. sub_st->id = pes->pid;
  539. avpriv_set_pts_info(sub_st, 33, 1, 90000);
  540. sub_st->priv_data = sub_pes;
  541. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  542. sub_st->codec->codec_id = AV_CODEC_ID_AC3;
  543. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  544. sub_pes->sub_st = pes->sub_st = sub_st;
  545. }
  546. }
  547. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  548. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  549. return 0;
  550. }
  551. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  552. {
  553. av_init_packet(pkt);
  554. pkt->destruct = av_destruct_packet;
  555. pkt->data = pes->buffer;
  556. pkt->size = pes->data_index;
  557. if(pes->total_size != MAX_PES_PAYLOAD &&
  558. pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
  559. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  560. pes->flags |= AV_PKT_FLAG_CORRUPT;
  561. }
  562. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  563. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  564. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  565. pkt->stream_index = pes->sub_st->index;
  566. else
  567. pkt->stream_index = pes->st->index;
  568. pkt->pts = pes->pts;
  569. pkt->dts = pes->dts;
  570. /* store position of first TS packet of this PES packet */
  571. pkt->pos = pes->ts_packet_pos;
  572. pkt->flags = pes->flags;
  573. /* reset pts values */
  574. pes->pts = AV_NOPTS_VALUE;
  575. pes->dts = AV_NOPTS_VALUE;
  576. pes->buffer = NULL;
  577. pes->data_index = 0;
  578. pes->flags = 0;
  579. }
  580. static uint64_t get_bits64(GetBitContext *gb, int bits)
  581. {
  582. uint64_t ret = 0;
  583. while (bits > 17) {
  584. ret <<= 17;
  585. ret |= get_bits(gb, 17);
  586. bits -= 17;
  587. }
  588. ret <<= bits;
  589. ret |= get_bits(gb, bits);
  590. return ret;
  591. }
  592. static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
  593. {
  594. GetBitContext gb;
  595. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  596. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  597. int dts_flag = -1, cts_flag = -1;
  598. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  599. init_get_bits(&gb, buf, buf_size*8);
  600. if (sl->use_au_start)
  601. au_start_flag = get_bits1(&gb);
  602. if (sl->use_au_end)
  603. au_end_flag = get_bits1(&gb);
  604. if (!sl->use_au_start && !sl->use_au_end)
  605. au_start_flag = au_end_flag = 1;
  606. if (sl->ocr_len > 0)
  607. ocr_flag = get_bits1(&gb);
  608. if (sl->use_idle)
  609. idle_flag = get_bits1(&gb);
  610. if (sl->use_padding)
  611. padding_flag = get_bits1(&gb);
  612. if (padding_flag)
  613. padding_bits = get_bits(&gb, 3);
  614. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  615. if (sl->packet_seq_num_len)
  616. skip_bits_long(&gb, sl->packet_seq_num_len);
  617. if (sl->degr_prior_len)
  618. if (get_bits1(&gb))
  619. skip_bits(&gb, sl->degr_prior_len);
  620. if (ocr_flag)
  621. skip_bits_long(&gb, sl->ocr_len);
  622. if (au_start_flag) {
  623. if (sl->use_rand_acc_pt)
  624. get_bits1(&gb);
  625. if (sl->au_seq_num_len > 0)
  626. skip_bits_long(&gb, sl->au_seq_num_len);
  627. if (sl->use_timestamps) {
  628. dts_flag = get_bits1(&gb);
  629. cts_flag = get_bits1(&gb);
  630. }
  631. }
  632. if (sl->inst_bitrate_len)
  633. inst_bitrate_flag = get_bits1(&gb);
  634. if (dts_flag == 1)
  635. dts = get_bits64(&gb, sl->timestamp_len);
  636. if (cts_flag == 1)
  637. cts = get_bits64(&gb, sl->timestamp_len);
  638. if (sl->au_len > 0)
  639. skip_bits_long(&gb, sl->au_len);
  640. if (inst_bitrate_flag)
  641. skip_bits_long(&gb, sl->inst_bitrate_len);
  642. }
  643. if (dts != AV_NOPTS_VALUE)
  644. pes->dts = dts;
  645. if (cts != AV_NOPTS_VALUE)
  646. pes->pts = cts;
  647. if (sl->timestamp_len && sl->timestamp_res)
  648. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  649. return (get_bits_count(&gb) + 7) >> 3;
  650. }
  651. /* return non zero if a packet could be constructed */
  652. static int mpegts_push_data(MpegTSFilter *filter,
  653. const uint8_t *buf, int buf_size, int is_start,
  654. int64_t pos)
  655. {
  656. PESContext *pes = filter->u.pes_filter.opaque;
  657. MpegTSContext *ts = pes->ts;
  658. const uint8_t *p;
  659. int len, code;
  660. if(!ts->pkt)
  661. return 0;
  662. if (is_start) {
  663. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  664. new_pes_packet(pes, ts->pkt);
  665. ts->stop_parse = 1;
  666. }
  667. pes->state = MPEGTS_HEADER;
  668. pes->data_index = 0;
  669. pes->ts_packet_pos = pos;
  670. }
  671. p = buf;
  672. while (buf_size > 0) {
  673. switch(pes->state) {
  674. case MPEGTS_HEADER:
  675. len = PES_START_SIZE - pes->data_index;
  676. if (len > buf_size)
  677. len = buf_size;
  678. memcpy(pes->header + pes->data_index, p, len);
  679. pes->data_index += len;
  680. p += len;
  681. buf_size -= len;
  682. if (pes->data_index == PES_START_SIZE) {
  683. /* we got all the PES or section header. We can now
  684. decide */
  685. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  686. pes->header[2] == 0x01) {
  687. /* it must be an mpeg2 PES stream */
  688. code = pes->header[3] | 0x100;
  689. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  690. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  691. (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
  692. code == 0x1be) /* padding_stream */
  693. goto skip;
  694. /* stream not present in PMT */
  695. if (!pes->st) {
  696. pes->st = avformat_new_stream(ts->stream, NULL);
  697. if (!pes->st)
  698. return AVERROR(ENOMEM);
  699. pes->st->id = pes->pid;
  700. mpegts_set_stream_info(pes->st, pes, 0, 0);
  701. }
  702. pes->total_size = AV_RB16(pes->header + 4);
  703. /* NOTE: a zero total size means the PES size is
  704. unbounded */
  705. if (!pes->total_size)
  706. pes->total_size = MAX_PES_PAYLOAD;
  707. /* allocate pes buffer */
  708. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  709. if (!pes->buffer)
  710. return AVERROR(ENOMEM);
  711. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  712. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  713. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  714. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  715. pes->state = MPEGTS_PESHEADER;
  716. if (pes->st->codec->codec_id == AV_CODEC_ID_NONE) {
  717. av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
  718. pes->pid, pes->stream_type);
  719. pes->st->codec->codec_id = AV_CODEC_ID_PROBE;
  720. }
  721. } else {
  722. pes->state = MPEGTS_PAYLOAD;
  723. pes->data_index = 0;
  724. }
  725. } else {
  726. /* otherwise, it should be a table */
  727. /* skip packet */
  728. skip:
  729. pes->state = MPEGTS_SKIP;
  730. continue;
  731. }
  732. }
  733. break;
  734. /**********************************************/
  735. /* PES packing parsing */
  736. case MPEGTS_PESHEADER:
  737. len = PES_HEADER_SIZE - pes->data_index;
  738. if (len < 0)
  739. return -1;
  740. if (len > buf_size)
  741. len = buf_size;
  742. memcpy(pes->header + pes->data_index, p, len);
  743. pes->data_index += len;
  744. p += len;
  745. buf_size -= len;
  746. if (pes->data_index == PES_HEADER_SIZE) {
  747. pes->pes_header_size = pes->header[8] + 9;
  748. pes->state = MPEGTS_PESHEADER_FILL;
  749. }
  750. break;
  751. case MPEGTS_PESHEADER_FILL:
  752. len = pes->pes_header_size - pes->data_index;
  753. if (len < 0)
  754. return -1;
  755. if (len > buf_size)
  756. len = buf_size;
  757. memcpy(pes->header + pes->data_index, p, len);
  758. pes->data_index += len;
  759. p += len;
  760. buf_size -= len;
  761. if (pes->data_index == pes->pes_header_size) {
  762. const uint8_t *r;
  763. unsigned int flags, pes_ext, skip;
  764. flags = pes->header[7];
  765. r = pes->header + 9;
  766. pes->pts = AV_NOPTS_VALUE;
  767. pes->dts = AV_NOPTS_VALUE;
  768. if ((flags & 0xc0) == 0x80) {
  769. pes->dts = pes->pts = ff_parse_pes_pts(r);
  770. r += 5;
  771. } else if ((flags & 0xc0) == 0xc0) {
  772. pes->pts = ff_parse_pes_pts(r);
  773. r += 5;
  774. pes->dts = ff_parse_pes_pts(r);
  775. r += 5;
  776. }
  777. pes->extended_stream_id = -1;
  778. if (flags & 0x01) { /* PES extension */
  779. pes_ext = *r++;
  780. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  781. skip = (pes_ext >> 4) & 0xb;
  782. skip += skip & 0x9;
  783. r += skip;
  784. if ((pes_ext & 0x41) == 0x01 &&
  785. (r + 2) <= (pes->header + pes->pes_header_size)) {
  786. /* PES extension 2 */
  787. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  788. pes->extended_stream_id = r[1];
  789. }
  790. }
  791. /* we got the full header. We parse it and get the payload */
  792. pes->state = MPEGTS_PAYLOAD;
  793. pes->data_index = 0;
  794. if (pes->stream_type == 0x12 && buf_size > 0) {
  795. int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
  796. pes->pes_header_size += sl_header_bytes;
  797. p += sl_header_bytes;
  798. buf_size -= sl_header_bytes;
  799. }
  800. }
  801. break;
  802. case MPEGTS_PAYLOAD:
  803. if (buf_size > 0 && pes->buffer) {
  804. if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
  805. new_pes_packet(pes, ts->pkt);
  806. pes->total_size = MAX_PES_PAYLOAD;
  807. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  808. if (!pes->buffer)
  809. return AVERROR(ENOMEM);
  810. ts->stop_parse = 1;
  811. } else if (pes->data_index == 0 && buf_size > pes->total_size) {
  812. // pes packet size is < ts size packet and pes data is padded with 0xff
  813. // not sure if this is legal in ts but see issue #2392
  814. buf_size = pes->total_size;
  815. }
  816. memcpy(pes->buffer+pes->data_index, p, buf_size);
  817. pes->data_index += buf_size;
  818. }
  819. buf_size = 0;
  820. /* emit complete packets with known packet size
  821. * decreases demuxer delay for infrequent packets like subtitles from
  822. * a couple of seconds to milliseconds for properly muxed files.
  823. * total_size is the number of bytes following pes_packet_length
  824. * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
  825. if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  826. pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
  827. ts->stop_parse = 1;
  828. new_pes_packet(pes, ts->pkt);
  829. }
  830. break;
  831. case MPEGTS_SKIP:
  832. buf_size = 0;
  833. break;
  834. }
  835. }
  836. return 0;
  837. }
  838. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  839. {
  840. MpegTSFilter *tss;
  841. PESContext *pes;
  842. /* if no pid found, then add a pid context */
  843. pes = av_mallocz(sizeof(PESContext));
  844. if (!pes)
  845. return 0;
  846. pes->ts = ts;
  847. pes->stream = ts->stream;
  848. pes->pid = pid;
  849. pes->pcr_pid = pcr_pid;
  850. pes->state = MPEGTS_SKIP;
  851. pes->pts = AV_NOPTS_VALUE;
  852. pes->dts = AV_NOPTS_VALUE;
  853. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  854. if (!tss) {
  855. av_free(pes);
  856. return 0;
  857. }
  858. return pes;
  859. }
  860. #define MAX_LEVEL 4
  861. typedef struct {
  862. AVFormatContext *s;
  863. AVIOContext pb;
  864. Mp4Descr *descr;
  865. Mp4Descr *active_descr;
  866. int descr_count;
  867. int max_descr_count;
  868. int level;
  869. } MP4DescrParseContext;
  870. static int init_MP4DescrParseContext(
  871. MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
  872. unsigned size, Mp4Descr *descr, int max_descr_count)
  873. {
  874. int ret;
  875. if (size > (1<<30))
  876. return AVERROR_INVALIDDATA;
  877. if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
  878. NULL, NULL, NULL, NULL)) < 0)
  879. return ret;
  880. d->s = s;
  881. d->level = 0;
  882. d->descr_count = 0;
  883. d->descr = descr;
  884. d->active_descr = NULL;
  885. d->max_descr_count = max_descr_count;
  886. return 0;
  887. }
  888. static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
  889. int64_t new_off = avio_tell(pb);
  890. (*len) -= new_off - *off;
  891. *off = new_off;
  892. }
  893. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  894. int target_tag);
  895. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  896. {
  897. while (len > 0) {
  898. if (parse_mp4_descr(d, off, len, 0) < 0)
  899. return -1;
  900. update_offsets(&d->pb, &off, &len);
  901. }
  902. return 0;
  903. }
  904. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  905. {
  906. avio_rb16(&d->pb); // ID
  907. avio_r8(&d->pb);
  908. avio_r8(&d->pb);
  909. avio_r8(&d->pb);
  910. avio_r8(&d->pb);
  911. avio_r8(&d->pb);
  912. update_offsets(&d->pb, &off, &len);
  913. return parse_mp4_descr_arr(d, off, len);
  914. }
  915. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  916. {
  917. int id_flags;
  918. if (len < 2)
  919. return 0;
  920. id_flags = avio_rb16(&d->pb);
  921. if (!(id_flags & 0x0020)) { //URL_Flag
  922. update_offsets(&d->pb, &off, &len);
  923. return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
  924. } else {
  925. return 0;
  926. }
  927. }
  928. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  929. {
  930. int es_id = 0;
  931. if (d->descr_count >= d->max_descr_count)
  932. return -1;
  933. ff_mp4_parse_es_descr(&d->pb, &es_id);
  934. d->active_descr = d->descr + (d->descr_count++);
  935. d->active_descr->es_id = es_id;
  936. update_offsets(&d->pb, &off, &len);
  937. parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  938. update_offsets(&d->pb, &off, &len);
  939. if (len > 0)
  940. parse_mp4_descr(d, off, len, MP4SLDescrTag);
  941. d->active_descr = NULL;
  942. return 0;
  943. }
  944. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  945. {
  946. Mp4Descr *descr = d->active_descr;
  947. if (!descr)
  948. return -1;
  949. d->active_descr->dec_config_descr = av_malloc(len);
  950. if (!descr->dec_config_descr)
  951. return AVERROR(ENOMEM);
  952. descr->dec_config_descr_len = len;
  953. avio_read(&d->pb, descr->dec_config_descr, len);
  954. return 0;
  955. }
  956. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  957. {
  958. Mp4Descr *descr = d->active_descr;
  959. int predefined;
  960. if (!descr)
  961. return -1;
  962. predefined = avio_r8(&d->pb);
  963. if (!predefined) {
  964. int lengths;
  965. int flags = avio_r8(&d->pb);
  966. descr->sl.use_au_start = !!(flags & 0x80);
  967. descr->sl.use_au_end = !!(flags & 0x40);
  968. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  969. descr->sl.use_padding = !!(flags & 0x08);
  970. descr->sl.use_timestamps = !!(flags & 0x04);
  971. descr->sl.use_idle = !!(flags & 0x02);
  972. descr->sl.timestamp_res = avio_rb32(&d->pb);
  973. avio_rb32(&d->pb);
  974. descr->sl.timestamp_len = avio_r8(&d->pb);
  975. descr->sl.ocr_len = avio_r8(&d->pb);
  976. descr->sl.au_len = avio_r8(&d->pb);
  977. descr->sl.inst_bitrate_len = avio_r8(&d->pb);
  978. lengths = avio_rb16(&d->pb);
  979. descr->sl.degr_prior_len = lengths >> 12;
  980. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  981. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  982. } else {
  983. av_log_missing_feature(d->s, "Predefined SLConfigDescriptor\n", 0);
  984. }
  985. return 0;
  986. }
  987. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  988. int target_tag) {
  989. int tag;
  990. int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  991. update_offsets(&d->pb, &off, &len);
  992. if (len < 0 || len1 > len || len1 <= 0) {
  993. av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
  994. return -1;
  995. }
  996. if (d->level++ >= MAX_LEVEL) {
  997. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  998. goto done;
  999. }
  1000. if (target_tag && tag != target_tag) {
  1001. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
  1002. goto done;
  1003. }
  1004. switch (tag) {
  1005. case MP4IODescrTag:
  1006. parse_MP4IODescrTag(d, off, len1);
  1007. break;
  1008. case MP4ODescrTag:
  1009. parse_MP4ODescrTag(d, off, len1);
  1010. break;
  1011. case MP4ESDescrTag:
  1012. parse_MP4ESDescrTag(d, off, len1);
  1013. break;
  1014. case MP4DecConfigDescrTag:
  1015. parse_MP4DecConfigDescrTag(d, off, len1);
  1016. break;
  1017. case MP4SLDescrTag:
  1018. parse_MP4SLDescrTag(d, off, len1);
  1019. break;
  1020. }
  1021. done:
  1022. d->level--;
  1023. avio_seek(&d->pb, off + len1, SEEK_SET);
  1024. return 0;
  1025. }
  1026. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1027. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1028. {
  1029. MP4DescrParseContext d;
  1030. if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1031. return -1;
  1032. parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1033. *descr_count = d.descr_count;
  1034. return 0;
  1035. }
  1036. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1037. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1038. {
  1039. MP4DescrParseContext d;
  1040. if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1041. return -1;
  1042. parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1043. *descr_count = d.descr_count;
  1044. return 0;
  1045. }
  1046. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1047. {
  1048. MpegTSContext *ts = filter->u.section_filter.opaque;
  1049. SectionHeader h;
  1050. const uint8_t *p, *p_end;
  1051. AVIOContext pb;
  1052. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1053. int mp4_descr_count = 0;
  1054. int i, pid;
  1055. AVFormatContext *s = ts->stream;
  1056. p_end = section + section_len - 4;
  1057. p = section;
  1058. if (parse_section_header(&h, &p, p_end) < 0)
  1059. return;
  1060. if (h.tid != M4OD_TID)
  1061. return;
  1062. mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1063. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1064. if (!ts->pids[pid])
  1065. continue;
  1066. for (i = 0; i < mp4_descr_count; i++) {
  1067. PESContext *pes;
  1068. AVStream *st;
  1069. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1070. continue;
  1071. if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
  1072. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1073. continue;
  1074. }
  1075. pes = ts->pids[pid]->u.pes_filter.opaque;
  1076. st = pes->st;
  1077. if (!st) {
  1078. continue;
  1079. }
  1080. pes->sl = mp4_descr[i].sl;
  1081. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1082. mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1083. ff_mp4_read_dec_config_descr(s, st, &pb);
  1084. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1085. st->codec->extradata_size > 0)
  1086. st->need_parsing = 0;
  1087. if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1088. st->codec->extradata_size > 0)
  1089. st->need_parsing = 0;
  1090. if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1091. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
  1092. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1093. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
  1094. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1095. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
  1096. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1097. }
  1098. }
  1099. }
  1100. for (i = 0; i < mp4_descr_count; i++)
  1101. av_free(mp4_descr[i].dec_config_descr);
  1102. }
  1103. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1104. const uint8_t **pp, const uint8_t *desc_list_end,
  1105. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1106. MpegTSContext *ts)
  1107. {
  1108. const uint8_t *desc_end;
  1109. int desc_len, desc_tag, desc_es_id;
  1110. char language[252];
  1111. int i;
  1112. desc_tag = get8(pp, desc_list_end);
  1113. if (desc_tag < 0)
  1114. return -1;
  1115. desc_len = get8(pp, desc_list_end);
  1116. if (desc_len < 0)
  1117. return -1;
  1118. desc_end = *pp + desc_len;
  1119. if (desc_end > desc_list_end)
  1120. return -1;
  1121. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1122. if (st->codec->codec_id == AV_CODEC_ID_NONE &&
  1123. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1124. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1125. switch(desc_tag) {
  1126. case 0x1E: /* SL descriptor */
  1127. desc_es_id = get16(pp, desc_end);
  1128. if (ts && ts->pids[pid])
  1129. ts->pids[pid]->es_id = desc_es_id;
  1130. for (i = 0; i < mp4_descr_count; i++)
  1131. if (mp4_descr[i].dec_config_descr_len &&
  1132. mp4_descr[i].es_id == desc_es_id) {
  1133. AVIOContext pb;
  1134. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1135. mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1136. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1137. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1138. st->codec->extradata_size > 0)
  1139. st->need_parsing = 0;
  1140. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1141. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1142. }
  1143. break;
  1144. case 0x1F: /* FMC descriptor */
  1145. get16(pp, desc_end);
  1146. if (mp4_descr_count > 0 && st->codec->codec_id == AV_CODEC_ID_AAC_LATM &&
  1147. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1148. AVIOContext pb;
  1149. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1150. mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1151. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1152. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1153. st->codec->extradata_size > 0)
  1154. st->need_parsing = 0;
  1155. }
  1156. break;
  1157. case 0x56: /* DVB teletext descriptor */
  1158. language[0] = get8(pp, desc_end);
  1159. language[1] = get8(pp, desc_end);
  1160. language[2] = get8(pp, desc_end);
  1161. language[3] = 0;
  1162. av_dict_set(&st->metadata, "language", language, 0);
  1163. break;
  1164. case 0x59: /* subtitling descriptor */
  1165. language[0] = get8(pp, desc_end);
  1166. language[1] = get8(pp, desc_end);
  1167. language[2] = get8(pp, desc_end);
  1168. language[3] = 0;
  1169. /* hearing impaired subtitles detection */
  1170. switch(get8(pp, desc_end)) {
  1171. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1172. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1173. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1174. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1175. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1176. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1177. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1178. break;
  1179. }
  1180. if (st->codec->extradata) {
  1181. if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
  1182. av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
  1183. } else {
  1184. st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
  1185. if (st->codec->extradata) {
  1186. st->codec->extradata_size = 4;
  1187. memcpy(st->codec->extradata, *pp, 4);
  1188. }
  1189. }
  1190. *pp += 4;
  1191. av_dict_set(&st->metadata, "language", language, 0);
  1192. break;
  1193. case 0x0a: /* ISO 639 language descriptor */
  1194. for (i = 0; i + 4 <= desc_len; i += 4) {
  1195. language[i + 0] = get8(pp, desc_end);
  1196. language[i + 1] = get8(pp, desc_end);
  1197. language[i + 2] = get8(pp, desc_end);
  1198. language[i + 3] = ',';
  1199. switch (get8(pp, desc_end)) {
  1200. case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
  1201. case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
  1202. case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
  1203. }
  1204. }
  1205. if (i) {
  1206. language[i - 1] = 0;
  1207. av_dict_set(&st->metadata, "language", language, 0);
  1208. }
  1209. break;
  1210. case 0x05: /* registration descriptor */
  1211. st->codec->codec_tag = bytestream_get_le32(pp);
  1212. av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  1213. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1214. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1215. break;
  1216. default:
  1217. break;
  1218. }
  1219. *pp = desc_end;
  1220. return 0;
  1221. }
  1222. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1223. {
  1224. MpegTSContext *ts = filter->u.section_filter.opaque;
  1225. SectionHeader h1, *h = &h1;
  1226. PESContext *pes;
  1227. AVStream *st;
  1228. const uint8_t *p, *p_end, *desc_list_end;
  1229. int program_info_length, pcr_pid, pid, stream_type;
  1230. int desc_list_len;
  1231. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1232. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1233. int mp4_descr_count = 0;
  1234. int i;
  1235. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1236. hex_dump_debug(ts->stream, section, section_len);
  1237. p_end = section + section_len - 4;
  1238. p = section;
  1239. if (parse_section_header(h, &p, p_end) < 0)
  1240. return;
  1241. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1242. h->id, h->sec_num, h->last_sec_num);
  1243. if (h->tid != PMT_TID)
  1244. return;
  1245. clear_program(ts, h->id);
  1246. pcr_pid = get16(&p, p_end);
  1247. if (pcr_pid < 0)
  1248. return;
  1249. pcr_pid &= 0x1fff;
  1250. add_pid_to_pmt(ts, h->id, pcr_pid);
  1251. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1252. program_info_length = get16(&p, p_end);
  1253. if (program_info_length < 0)
  1254. return;
  1255. program_info_length &= 0xfff;
  1256. while(program_info_length >= 2) {
  1257. uint8_t tag, len;
  1258. tag = get8(&p, p_end);
  1259. len = get8(&p, p_end);
  1260. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1261. if(len > program_info_length - 2)
  1262. //something else is broken, exit the program_descriptors_loop
  1263. break;
  1264. program_info_length -= len + 2;
  1265. if (tag == 0x1d) { // IOD descriptor
  1266. get8(&p, p_end); // scope
  1267. get8(&p, p_end); // label
  1268. len -= 2;
  1269. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1270. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1271. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1272. prog_reg_desc = bytestream_get_le32(&p);
  1273. len -= 4;
  1274. }
  1275. p += len;
  1276. }
  1277. p += program_info_length;
  1278. if (p >= p_end)
  1279. goto out;
  1280. // stop parsing after pmt, we found header
  1281. if (!ts->stream->nb_streams)
  1282. ts->stop_parse = 1;
  1283. for(;;) {
  1284. st = 0;
  1285. pes = NULL;
  1286. stream_type = get8(&p, p_end);
  1287. if (stream_type < 0)
  1288. break;
  1289. pid = get16(&p, p_end);
  1290. if (pid < 0)
  1291. break;
  1292. pid &= 0x1fff;
  1293. /* now create stream */
  1294. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1295. pes = ts->pids[pid]->u.pes_filter.opaque;
  1296. if (!pes->st) {
  1297. pes->st = avformat_new_stream(pes->stream, NULL);
  1298. pes->st->id = pes->pid;
  1299. }
  1300. st = pes->st;
  1301. } else if (stream_type != 0x13) {
  1302. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  1303. pes = add_pes_stream(ts, pid, pcr_pid);
  1304. if (pes) {
  1305. st = avformat_new_stream(pes->stream, NULL);
  1306. st->id = pes->pid;
  1307. }
  1308. } else {
  1309. int idx = ff_find_stream_index(ts->stream, pid);
  1310. if (idx >= 0) {
  1311. st = ts->stream->streams[idx];
  1312. } else {
  1313. st = avformat_new_stream(ts->stream, NULL);
  1314. st->id = pid;
  1315. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1316. }
  1317. }
  1318. if (!st)
  1319. goto out;
  1320. if (pes && !pes->stream_type)
  1321. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1322. add_pid_to_pmt(ts, h->id, pid);
  1323. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1324. desc_list_len = get16(&p, p_end);
  1325. if (desc_list_len < 0)
  1326. break;
  1327. desc_list_len &= 0xfff;
  1328. desc_list_end = p + desc_list_len;
  1329. if (desc_list_end > p_end)
  1330. break;
  1331. for(;;) {
  1332. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
  1333. mp4_descr, mp4_descr_count, pid, ts) < 0)
  1334. break;
  1335. if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  1336. ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  1337. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1338. }
  1339. }
  1340. p = desc_list_end;
  1341. }
  1342. out:
  1343. for (i = 0; i < mp4_descr_count; i++)
  1344. av_free(mp4_descr[i].dec_config_descr);
  1345. }
  1346. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1347. {
  1348. MpegTSContext *ts = filter->u.section_filter.opaque;
  1349. SectionHeader h1, *h = &h1;
  1350. const uint8_t *p, *p_end;
  1351. int sid, pmt_pid;
  1352. av_dlog(ts->stream, "PAT:\n");
  1353. hex_dump_debug(ts->stream, section, section_len);
  1354. p_end = section + section_len - 4;
  1355. p = section;
  1356. if (parse_section_header(h, &p, p_end) < 0)
  1357. return;
  1358. if (h->tid != PAT_TID)
  1359. return;
  1360. clear_programs(ts);
  1361. for(;;) {
  1362. sid = get16(&p, p_end);
  1363. if (sid < 0)
  1364. break;
  1365. pmt_pid = get16(&p, p_end);
  1366. if (pmt_pid < 0)
  1367. break;
  1368. pmt_pid &= 0x1fff;
  1369. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1370. if (sid == 0x0000) {
  1371. /* NIT info */
  1372. } else {
  1373. av_new_program(ts->stream, sid);
  1374. if (ts->pids[pmt_pid])
  1375. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1376. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1377. add_pat_entry(ts, sid);
  1378. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  1379. add_pid_to_pmt(ts, sid, pmt_pid);
  1380. }
  1381. }
  1382. }
  1383. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1384. {
  1385. MpegTSContext *ts = filter->u.section_filter.opaque;
  1386. SectionHeader h1, *h = &h1;
  1387. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1388. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1389. char *name, *provider_name;
  1390. av_dlog(ts->stream, "SDT:\n");
  1391. hex_dump_debug(ts->stream, section, section_len);
  1392. p_end = section + section_len - 4;
  1393. p = section;
  1394. if (parse_section_header(h, &p, p_end) < 0)
  1395. return;
  1396. if (h->tid != SDT_TID)
  1397. return;
  1398. onid = get16(&p, p_end);
  1399. if (onid < 0)
  1400. return;
  1401. val = get8(&p, p_end);
  1402. if (val < 0)
  1403. return;
  1404. for(;;) {
  1405. sid = get16(&p, p_end);
  1406. if (sid < 0)
  1407. break;
  1408. val = get8(&p, p_end);
  1409. if (val < 0)
  1410. break;
  1411. desc_list_len = get16(&p, p_end);
  1412. if (desc_list_len < 0)
  1413. break;
  1414. desc_list_len &= 0xfff;
  1415. desc_list_end = p + desc_list_len;
  1416. if (desc_list_end > p_end)
  1417. break;
  1418. for(;;) {
  1419. desc_tag = get8(&p, desc_list_end);
  1420. if (desc_tag < 0)
  1421. break;
  1422. desc_len = get8(&p, desc_list_end);
  1423. desc_end = p + desc_len;
  1424. if (desc_end > desc_list_end)
  1425. break;
  1426. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1427. desc_tag, desc_len);
  1428. switch(desc_tag) {
  1429. case 0x48:
  1430. service_type = get8(&p, p_end);
  1431. if (service_type < 0)
  1432. break;
  1433. provider_name = getstr8(&p, p_end);
  1434. if (!provider_name)
  1435. break;
  1436. name = getstr8(&p, p_end);
  1437. if (name) {
  1438. AVProgram *program = av_new_program(ts->stream, sid);
  1439. if(program) {
  1440. av_dict_set(&program->metadata, "service_name", name, 0);
  1441. av_dict_set(&program->metadata, "service_provider", provider_name, 0);
  1442. }
  1443. }
  1444. av_free(name);
  1445. av_free(provider_name);
  1446. break;
  1447. default:
  1448. break;
  1449. }
  1450. p = desc_end;
  1451. }
  1452. p = desc_list_end;
  1453. }
  1454. }
  1455. /* handle one TS packet */
  1456. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1457. {
  1458. AVFormatContext *s = ts->stream;
  1459. MpegTSFilter *tss;
  1460. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1461. has_adaptation, has_payload;
  1462. const uint8_t *p, *p_end;
  1463. int64_t pos;
  1464. pid = AV_RB16(packet + 1) & 0x1fff;
  1465. if(pid && discard_pid(ts, pid))
  1466. return 0;
  1467. is_start = packet[1] & 0x40;
  1468. tss = ts->pids[pid];
  1469. if (ts->auto_guess && tss == NULL && is_start) {
  1470. add_pes_stream(ts, pid, -1);
  1471. tss = ts->pids[pid];
  1472. }
  1473. if (!tss)
  1474. return 0;
  1475. afc = (packet[3] >> 4) & 3;
  1476. if (afc == 0) /* reserved value */
  1477. return 0;
  1478. has_adaptation = afc & 2;
  1479. has_payload = afc & 1;
  1480. is_discontinuity = has_adaptation
  1481. && packet[4] != 0 /* with length > 0 */
  1482. && (packet[5] & 0x80); /* and discontinuity indicated */
  1483. /* continuity check (currently not used) */
  1484. cc = (packet[3] & 0xf);
  1485. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1486. cc_ok = pid == 0x1FFF // null packet PID
  1487. || is_discontinuity
  1488. || tss->last_cc < 0
  1489. || expected_cc == cc;
  1490. tss->last_cc = cc;
  1491. if (!cc_ok) {
  1492. av_log(ts->stream, AV_LOG_WARNING,
  1493. "Continuity check failed for pid %d expected %d got %d\n",
  1494. pid, expected_cc, cc);
  1495. if(tss->type == MPEGTS_PES) {
  1496. PESContext *pc = tss->u.pes_filter.opaque;
  1497. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1498. }
  1499. }
  1500. if (!has_payload)
  1501. return 0;
  1502. p = packet + 4;
  1503. if (has_adaptation) {
  1504. /* skip adaptation field */
  1505. p += p[0] + 1;
  1506. }
  1507. /* if past the end of packet, ignore */
  1508. p_end = packet + TS_PACKET_SIZE;
  1509. if (p >= p_end)
  1510. return 0;
  1511. pos = avio_tell(ts->stream->pb);
  1512. ts->pos47= pos % ts->raw_packet_size;
  1513. if (tss->type == MPEGTS_SECTION) {
  1514. if (is_start) {
  1515. /* pointer field present */
  1516. len = *p++;
  1517. if (p + len > p_end)
  1518. return 0;
  1519. if (len && cc_ok) {
  1520. /* write remaining section bytes */
  1521. write_section_data(s, tss,
  1522. p, len, 0);
  1523. /* check whether filter has been closed */
  1524. if (!ts->pids[pid])
  1525. return 0;
  1526. }
  1527. p += len;
  1528. if (p < p_end) {
  1529. write_section_data(s, tss,
  1530. p, p_end - p, 1);
  1531. }
  1532. } else {
  1533. if (cc_ok) {
  1534. write_section_data(s, tss,
  1535. p, p_end - p, 0);
  1536. }
  1537. }
  1538. } else {
  1539. int ret;
  1540. // Note: The position here points actually behind the current packet.
  1541. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1542. pos - ts->raw_packet_size)) < 0)
  1543. return ret;
  1544. }
  1545. return 0;
  1546. }
  1547. /* XXX: try to find a better synchro over several packets (use
  1548. get_packet_size() ?) */
  1549. static int mpegts_resync(AVFormatContext *s)
  1550. {
  1551. AVIOContext *pb = s->pb;
  1552. int c, i;
  1553. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1554. c = avio_r8(pb);
  1555. if (pb->eof_reached)
  1556. return -1;
  1557. if (c == 0x47) {
  1558. avio_seek(pb, -1, SEEK_CUR);
  1559. return 0;
  1560. }
  1561. }
  1562. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1563. /* no sync found */
  1564. return -1;
  1565. }
  1566. /* return -1 if error or EOF. Return 0 if OK. */
  1567. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1568. {
  1569. AVIOContext *pb = s->pb;
  1570. int skip, len;
  1571. for(;;) {
  1572. len = avio_read(pb, buf, TS_PACKET_SIZE);
  1573. if (len != TS_PACKET_SIZE)
  1574. return len < 0 ? len : AVERROR_EOF;
  1575. /* check packet sync byte */
  1576. if (buf[0] != 0x47) {
  1577. /* find a new packet start */
  1578. avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1579. if (mpegts_resync(s) < 0)
  1580. return AVERROR(EAGAIN);
  1581. else
  1582. continue;
  1583. } else {
  1584. skip = raw_packet_size - TS_PACKET_SIZE;
  1585. if (skip > 0)
  1586. avio_skip(pb, skip);
  1587. break;
  1588. }
  1589. }
  1590. return 0;
  1591. }
  1592. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1593. {
  1594. AVFormatContext *s = ts->stream;
  1595. uint8_t packet[TS_PACKET_SIZE+FF_INPUT_BUFFER_PADDING_SIZE];
  1596. int packet_num, ret = 0;
  1597. if (avio_tell(s->pb) != ts->last_pos) {
  1598. int i;
  1599. av_dlog(ts->stream, "Skipping after seek\n");
  1600. /* seek detected, flush pes buffer */
  1601. for (i = 0; i < NB_PID_MAX; i++) {
  1602. if (ts->pids[i]) {
  1603. if (ts->pids[i]->type == MPEGTS_PES) {
  1604. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1605. av_freep(&pes->buffer);
  1606. pes->data_index = 0;
  1607. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1608. }
  1609. ts->pids[i]->last_cc = -1;
  1610. }
  1611. }
  1612. }
  1613. ts->stop_parse = 0;
  1614. packet_num = 0;
  1615. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  1616. for(;;) {
  1617. if (ts->stop_parse>0)
  1618. break;
  1619. packet_num++;
  1620. if (nb_packets != 0 && packet_num >= nb_packets)
  1621. break;
  1622. ret = read_packet(s, packet, ts->raw_packet_size);
  1623. if (ret != 0)
  1624. break;
  1625. ret = handle_packet(ts, packet);
  1626. if (ret != 0)
  1627. break;
  1628. }
  1629. ts->last_pos = avio_tell(s->pb);
  1630. return ret;
  1631. }
  1632. static int mpegts_probe(AVProbeData *p)
  1633. {
  1634. const int size= p->buf_size;
  1635. int score, fec_score, dvhs_score;
  1636. int check_count= size / TS_FEC_PACKET_SIZE;
  1637. #define CHECK_COUNT 10
  1638. if (check_count < CHECK_COUNT)
  1639. return -1;
  1640. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1641. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1642. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1643. av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  1644. score, dvhs_score, fec_score);
  1645. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1646. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1647. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1648. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1649. else return -1;
  1650. }
  1651. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1652. (-1) if not available */
  1653. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1654. const uint8_t *packet)
  1655. {
  1656. int afc, len, flags;
  1657. const uint8_t *p;
  1658. unsigned int v;
  1659. afc = (packet[3] >> 4) & 3;
  1660. if (afc <= 1)
  1661. return -1;
  1662. p = packet + 4;
  1663. len = p[0];
  1664. p++;
  1665. if (len == 0)
  1666. return -1;
  1667. flags = *p++;
  1668. len--;
  1669. if (!(flags & 0x10))
  1670. return -1;
  1671. if (len < 6)
  1672. return -1;
  1673. v = AV_RB32(p);
  1674. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1675. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1676. return 0;
  1677. }
  1678. static int mpegts_read_header(AVFormatContext *s)
  1679. {
  1680. MpegTSContext *ts = s->priv_data;
  1681. AVIOContext *pb = s->pb;
  1682. uint8_t buf[5*1024];
  1683. int len;
  1684. int64_t pos;
  1685. /* read the first 1024 bytes to get packet size */
  1686. pos = avio_tell(pb);
  1687. len = avio_read(pb, buf, sizeof(buf));
  1688. if (len != sizeof(buf))
  1689. goto fail;
  1690. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1691. if (ts->raw_packet_size <= 0)
  1692. goto fail;
  1693. ts->stream = s;
  1694. ts->auto_guess = 0;
  1695. if (s->iformat == &ff_mpegts_demuxer) {
  1696. /* normal demux */
  1697. /* first do a scan to get all the services */
  1698. if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
  1699. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1700. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1701. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1702. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1703. /* if could not find service, enable auto_guess */
  1704. ts->auto_guess = 1;
  1705. av_dlog(ts->stream, "tuning done\n");
  1706. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1707. } else {
  1708. AVStream *st;
  1709. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1710. int64_t pcrs[2], pcr_h;
  1711. int packet_count[2];
  1712. uint8_t packet[TS_PACKET_SIZE];
  1713. /* only read packets */
  1714. st = avformat_new_stream(s, NULL);
  1715. if (!st)
  1716. goto fail;
  1717. avpriv_set_pts_info(st, 60, 1, 27000000);
  1718. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1719. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  1720. /* we iterate until we find two PCRs to estimate the bitrate */
  1721. pcr_pid = -1;
  1722. nb_pcrs = 0;
  1723. nb_packets = 0;
  1724. for(;;) {
  1725. ret = read_packet(s, packet, ts->raw_packet_size);
  1726. if (ret < 0)
  1727. return -1;
  1728. pid = AV_RB16(packet + 1) & 0x1fff;
  1729. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1730. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1731. pcr_pid = pid;
  1732. packet_count[nb_pcrs] = nb_packets;
  1733. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1734. nb_pcrs++;
  1735. if (nb_pcrs >= 2)
  1736. break;
  1737. }
  1738. nb_packets++;
  1739. }
  1740. /* NOTE1: the bitrate is computed without the FEC */
  1741. /* NOTE2: it is only the bitrate of the start of the stream */
  1742. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1743. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1744. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1745. st->codec->bit_rate = s->bit_rate;
  1746. st->start_time = ts->cur_pcr;
  1747. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  1748. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1749. }
  1750. avio_seek(pb, pos, SEEK_SET);
  1751. return 0;
  1752. fail:
  1753. return -1;
  1754. }
  1755. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1756. static int mpegts_raw_read_packet(AVFormatContext *s,
  1757. AVPacket *pkt)
  1758. {
  1759. MpegTSContext *ts = s->priv_data;
  1760. int ret, i;
  1761. int64_t pcr_h, next_pcr_h, pos;
  1762. int pcr_l, next_pcr_l;
  1763. uint8_t pcr_buf[12];
  1764. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1765. return AVERROR(ENOMEM);
  1766. pkt->pos= avio_tell(s->pb);
  1767. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1768. if (ret < 0) {
  1769. av_free_packet(pkt);
  1770. return ret;
  1771. }
  1772. if (ts->mpeg2ts_compute_pcr) {
  1773. /* compute exact PCR for each packet */
  1774. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1775. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1776. pos = avio_tell(s->pb);
  1777. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1778. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1779. avio_read(s->pb, pcr_buf, 12);
  1780. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1781. /* XXX: not precise enough */
  1782. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1783. (i + 1);
  1784. break;
  1785. }
  1786. }
  1787. avio_seek(s->pb, pos, SEEK_SET);
  1788. /* no next PCR found: we use previous increment */
  1789. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1790. }
  1791. pkt->pts = ts->cur_pcr;
  1792. pkt->duration = ts->pcr_incr;
  1793. ts->cur_pcr += ts->pcr_incr;
  1794. }
  1795. pkt->stream_index = 0;
  1796. return 0;
  1797. }
  1798. static int mpegts_read_packet(AVFormatContext *s,
  1799. AVPacket *pkt)
  1800. {
  1801. MpegTSContext *ts = s->priv_data;
  1802. int ret, i;
  1803. pkt->size = -1;
  1804. ts->pkt = pkt;
  1805. ret = handle_packets(ts, 0);
  1806. if (ret < 0) {
  1807. /* flush pes data left */
  1808. for (i = 0; i < NB_PID_MAX; i++) {
  1809. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1810. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1811. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1812. new_pes_packet(pes, pkt);
  1813. pes->state = MPEGTS_SKIP;
  1814. ret = 0;
  1815. break;
  1816. }
  1817. }
  1818. }
  1819. }
  1820. if (!ret && pkt->size < 0)
  1821. ret = AVERROR(EINTR);
  1822. return ret;
  1823. }
  1824. static int mpegts_read_close(AVFormatContext *s)
  1825. {
  1826. MpegTSContext *ts = s->priv_data;
  1827. int i;
  1828. clear_programs(ts);
  1829. for(i=0;i<NB_PID_MAX;i++)
  1830. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1831. return 0;
  1832. }
  1833. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1834. int64_t *ppos, int64_t pos_limit)
  1835. {
  1836. MpegTSContext *ts = s->priv_data;
  1837. int64_t pos, timestamp;
  1838. uint8_t buf[TS_PACKET_SIZE];
  1839. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1840. const int find_next= 1;
  1841. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1842. if (find_next) {
  1843. for(;;) {
  1844. avio_seek(s->pb, pos, SEEK_SET);
  1845. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1846. return AV_NOPTS_VALUE;
  1847. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1848. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1849. break;
  1850. }
  1851. pos += ts->raw_packet_size;
  1852. }
  1853. } else {
  1854. for(;;) {
  1855. pos -= ts->raw_packet_size;
  1856. if (pos < 0)
  1857. return AV_NOPTS_VALUE;
  1858. avio_seek(s->pb, pos, SEEK_SET);
  1859. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1860. return AV_NOPTS_VALUE;
  1861. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1862. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1863. break;
  1864. }
  1865. }
  1866. }
  1867. *ppos = pos;
  1868. return timestamp;
  1869. }
  1870. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1871. MpegTSContext *ts = s->priv_data;
  1872. uint8_t buf[TS_PACKET_SIZE];
  1873. int64_t pos;
  1874. if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1875. return -1;
  1876. pos= avio_tell(s->pb);
  1877. for(;;) {
  1878. avio_seek(s->pb, pos, SEEK_SET);
  1879. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1880. return -1;
  1881. // pid = AV_RB16(buf + 1) & 0x1fff;
  1882. if(buf[1] & 0x40) break;
  1883. pos += ts->raw_packet_size;
  1884. }
  1885. avio_seek(s->pb, pos, SEEK_SET);
  1886. return 0;
  1887. }
  1888. /**************************************************************/
  1889. /* parsing functions - called from other demuxers such as RTP */
  1890. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1891. {
  1892. MpegTSContext *ts;
  1893. ts = av_mallocz(sizeof(MpegTSContext));
  1894. if (!ts)
  1895. return NULL;
  1896. /* no stream case, currently used by RTP */
  1897. ts->raw_packet_size = TS_PACKET_SIZE;
  1898. ts->stream = s;
  1899. ts->auto_guess = 1;
  1900. return ts;
  1901. }
  1902. /* return the consumed length if a packet was output, or -1 if no
  1903. packet is output */
  1904. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1905. const uint8_t *buf, int len)
  1906. {
  1907. int len1;
  1908. len1 = len;
  1909. ts->pkt = pkt;
  1910. ts->stop_parse = 0;
  1911. for(;;) {
  1912. if (ts->stop_parse>0)
  1913. break;
  1914. if (len < TS_PACKET_SIZE)
  1915. return -1;
  1916. if (buf[0] != 0x47) {
  1917. buf++;
  1918. len--;
  1919. } else {
  1920. handle_packet(ts, buf);
  1921. buf += TS_PACKET_SIZE;
  1922. len -= TS_PACKET_SIZE;
  1923. }
  1924. }
  1925. return len1 - len;
  1926. }
  1927. void ff_mpegts_parse_close(MpegTSContext *ts)
  1928. {
  1929. int i;
  1930. for(i=0;i<NB_PID_MAX;i++)
  1931. av_free(ts->pids[i]);
  1932. av_free(ts);
  1933. }
  1934. AVInputFormat ff_mpegts_demuxer = {
  1935. .name = "mpegts",
  1936. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  1937. .priv_data_size = sizeof(MpegTSContext),
  1938. .read_probe = mpegts_probe,
  1939. .read_header = mpegts_read_header,
  1940. .read_packet = mpegts_read_packet,
  1941. .read_close = mpegts_read_close,
  1942. .read_seek = read_seek,
  1943. .read_timestamp = mpegts_get_pcr,
  1944. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  1945. };
  1946. AVInputFormat ff_mpegtsraw_demuxer = {
  1947. .name = "mpegtsraw",
  1948. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  1949. .priv_data_size = sizeof(MpegTSContext),
  1950. .read_header = mpegts_read_header,
  1951. .read_packet = mpegts_raw_read_packet,
  1952. .read_close = mpegts_read_close,
  1953. .read_seek = read_seek,
  1954. .read_timestamp = mpegts_get_pcr,
  1955. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  1956. .priv_class = &mpegtsraw_class,
  1957. };