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.

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