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.

1786 lines
54KB

  1. /*
  2. * MPEG2 transport stream (aka DVB) demuxer
  3. * Copyright (c) 2002-2003 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. //#define DEBUG
  22. //#define DEBUG_SEEK
  23. //#define USE_SYNCPOINT_SEARCH
  24. #include "libavutil/crc.h"
  25. #include "libavutil/intreadwrite.h"
  26. #include "libavcodec/bytestream.h"
  27. #include "avformat.h"
  28. #include "mpegts.h"
  29. #include "internal.h"
  30. #include "seek.h"
  31. /* 1.0 second at 24Mbit/s */
  32. #define MAX_SCAN_PACKETS 32000
  33. /* maximum size in which we look for synchronisation if
  34. synchronisation is lost */
  35. #define MAX_RESYNC_SIZE 65536
  36. #define MAX_PES_PAYLOAD 200*1024
  37. enum MpegTSFilterType {
  38. MPEGTS_PES,
  39. MPEGTS_SECTION,
  40. };
  41. typedef struct MpegTSFilter MpegTSFilter;
  42. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
  43. typedef struct MpegTSPESFilter {
  44. PESCallback *pes_cb;
  45. void *opaque;
  46. } MpegTSPESFilter;
  47. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  48. typedef void SetServiceCallback(void *opaque, int ret);
  49. typedef struct MpegTSSectionFilter {
  50. int section_index;
  51. int section_h_size;
  52. uint8_t *section_buf;
  53. unsigned int check_crc:1;
  54. unsigned int end_of_section_reached:1;
  55. SectionCallback *section_cb;
  56. void *opaque;
  57. } MpegTSSectionFilter;
  58. struct MpegTSFilter {
  59. int pid;
  60. int last_cc; /* last cc code (-1 if first packet) */
  61. enum MpegTSFilterType type;
  62. union {
  63. MpegTSPESFilter pes_filter;
  64. MpegTSSectionFilter section_filter;
  65. } u;
  66. };
  67. #define MAX_PIDS_PER_PROGRAM 64
  68. struct Program {
  69. unsigned int id; //program id/service id
  70. unsigned int nb_pids;
  71. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  72. };
  73. struct MpegTSContext {
  74. /* user data */
  75. AVFormatContext *stream;
  76. /** raw packet size, including FEC if present */
  77. int raw_packet_size;
  78. int pos47;
  79. /** if true, all pids are analyzed to find streams */
  80. int auto_guess;
  81. /** compute exact PCR for each transport stream packet */
  82. int mpeg2ts_compute_pcr;
  83. int64_t cur_pcr; /**< used to estimate the exact PCR */
  84. int pcr_incr; /**< used to estimate the exact PCR */
  85. /* data needed to handle file based ts */
  86. /** stop parsing loop */
  87. int stop_parse;
  88. /** packet containing Audio/Video data */
  89. AVPacket *pkt;
  90. /** to detect seek */
  91. int64_t last_pos;
  92. /******************************************/
  93. /* private mpegts data */
  94. /* scan context */
  95. /** structure to keep track of Program->pids mapping */
  96. unsigned int nb_prg;
  97. struct Program *prg;
  98. /** filters for various streams specified by PMT + for the PAT and PMT */
  99. MpegTSFilter *pids[NB_PID_MAX];
  100. };
  101. /* TS stream handling */
  102. enum MpegTSState {
  103. MPEGTS_HEADER = 0,
  104. MPEGTS_PESHEADER,
  105. MPEGTS_PESHEADER_FILL,
  106. MPEGTS_PAYLOAD,
  107. MPEGTS_SKIP,
  108. };
  109. /* enough for PES header + length */
  110. #define PES_START_SIZE 6
  111. #define PES_HEADER_SIZE 9
  112. #define MAX_PES_HEADER_SIZE (9 + 255)
  113. typedef struct PESContext {
  114. int pid;
  115. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  116. int stream_type;
  117. MpegTSContext *ts;
  118. AVFormatContext *stream;
  119. AVStream *st;
  120. AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  121. enum MpegTSState state;
  122. /* used to get the format */
  123. int data_index;
  124. int total_size;
  125. int pes_header_size;
  126. int extended_stream_id;
  127. int64_t pts, dts;
  128. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  129. uint8_t header[MAX_PES_HEADER_SIZE];
  130. uint8_t *buffer;
  131. } PESContext;
  132. extern AVInputFormat mpegts_demuxer;
  133. static void clear_program(MpegTSContext *ts, unsigned int programid)
  134. {
  135. int i;
  136. for(i=0; i<ts->nb_prg; i++)
  137. if(ts->prg[i].id == programid)
  138. ts->prg[i].nb_pids = 0;
  139. }
  140. static void clear_programs(MpegTSContext *ts)
  141. {
  142. av_freep(&ts->prg);
  143. ts->nb_prg=0;
  144. }
  145. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  146. {
  147. struct Program *p;
  148. void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
  149. if(!tmp)
  150. return;
  151. ts->prg = tmp;
  152. p = &ts->prg[ts->nb_prg];
  153. p->id = programid;
  154. p->nb_pids = 0;
  155. ts->nb_prg++;
  156. }
  157. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  158. {
  159. int i;
  160. struct Program *p = NULL;
  161. for(i=0; i<ts->nb_prg; i++) {
  162. if(ts->prg[i].id == programid) {
  163. p = &ts->prg[i];
  164. break;
  165. }
  166. }
  167. if(!p)
  168. return;
  169. if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  170. return;
  171. p->pids[p->nb_pids++] = pid;
  172. }
  173. /**
  174. * \brief discard_pid() decides if the pid is to be discarded according
  175. * to caller's programs selection
  176. * \param ts : - TS context
  177. * \param pid : - pid
  178. * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  179. * 0 otherwise
  180. */
  181. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  182. {
  183. int i, j, k;
  184. int used = 0, discarded = 0;
  185. struct Program *p;
  186. for(i=0; i<ts->nb_prg; i++) {
  187. p = &ts->prg[i];
  188. for(j=0; j<p->nb_pids; j++) {
  189. if(p->pids[j] != pid)
  190. continue;
  191. //is program with id p->id set to be discarded?
  192. for(k=0; k<ts->stream->nb_programs; k++) {
  193. if(ts->stream->programs[k]->id == p->id) {
  194. if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  195. discarded++;
  196. else
  197. used++;
  198. }
  199. }
  200. }
  201. }
  202. return !used && discarded;
  203. }
  204. /**
  205. * Assemble PES packets out of TS packets, and then call the "section_cb"
  206. * function when they are complete.
  207. */
  208. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  209. const uint8_t *buf, int buf_size, int is_start)
  210. {
  211. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  212. int len;
  213. if (is_start) {
  214. memcpy(tss->section_buf, buf, buf_size);
  215. tss->section_index = buf_size;
  216. tss->section_h_size = -1;
  217. tss->end_of_section_reached = 0;
  218. } else {
  219. if (tss->end_of_section_reached)
  220. return;
  221. len = 4096 - tss->section_index;
  222. if (buf_size < len)
  223. len = buf_size;
  224. memcpy(tss->section_buf + tss->section_index, buf, len);
  225. tss->section_index += len;
  226. }
  227. /* compute section length if possible */
  228. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  229. len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  230. if (len > 4096)
  231. return;
  232. tss->section_h_size = len;
  233. }
  234. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  235. tss->end_of_section_reached = 1;
  236. if (!tss->check_crc ||
  237. av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
  238. tss->section_buf, tss->section_h_size) == 0)
  239. tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  240. }
  241. }
  242. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  243. SectionCallback *section_cb, void *opaque,
  244. int check_crc)
  245. {
  246. MpegTSFilter *filter;
  247. MpegTSSectionFilter *sec;
  248. dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
  249. if (pid >= NB_PID_MAX || ts->pids[pid])
  250. return NULL;
  251. filter = av_mallocz(sizeof(MpegTSFilter));
  252. if (!filter)
  253. return NULL;
  254. ts->pids[pid] = filter;
  255. filter->type = MPEGTS_SECTION;
  256. filter->pid = pid;
  257. filter->last_cc = -1;
  258. sec = &filter->u.section_filter;
  259. sec->section_cb = section_cb;
  260. sec->opaque = opaque;
  261. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  262. sec->check_crc = check_crc;
  263. if (!sec->section_buf) {
  264. av_free(filter);
  265. return NULL;
  266. }
  267. return filter;
  268. }
  269. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  270. PESCallback *pes_cb,
  271. void *opaque)
  272. {
  273. MpegTSFilter *filter;
  274. MpegTSPESFilter *pes;
  275. if (pid >= NB_PID_MAX || ts->pids[pid])
  276. return NULL;
  277. filter = av_mallocz(sizeof(MpegTSFilter));
  278. if (!filter)
  279. return NULL;
  280. ts->pids[pid] = filter;
  281. filter->type = MPEGTS_PES;
  282. filter->pid = pid;
  283. filter->last_cc = -1;
  284. pes = &filter->u.pes_filter;
  285. pes->pes_cb = pes_cb;
  286. pes->opaque = opaque;
  287. return filter;
  288. }
  289. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  290. {
  291. int pid;
  292. pid = filter->pid;
  293. if (filter->type == MPEGTS_SECTION)
  294. av_freep(&filter->u.section_filter.section_buf);
  295. else if (filter->type == MPEGTS_PES) {
  296. PESContext *pes = filter->u.pes_filter.opaque;
  297. av_freep(&pes->buffer);
  298. /* referenced private data will be freed later in
  299. * av_close_input_stream */
  300. if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  301. av_freep(&filter->u.pes_filter.opaque);
  302. }
  303. }
  304. av_free(filter);
  305. ts->pids[pid] = NULL;
  306. }
  307. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  308. int stat[TS_MAX_PACKET_SIZE];
  309. int i;
  310. int x=0;
  311. int best_score=0;
  312. memset(stat, 0, packet_size*sizeof(int));
  313. for(x=i=0; i<size-3; i++){
  314. if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
  315. stat[x]++;
  316. if(stat[x] > best_score){
  317. best_score= stat[x];
  318. if(index) *index= x;
  319. }
  320. }
  321. x++;
  322. if(x == packet_size) x= 0;
  323. }
  324. return best_score;
  325. }
  326. /* autodetect fec presence. Must have at least 1024 bytes */
  327. static int get_packet_size(const uint8_t *buf, int size)
  328. {
  329. int score, fec_score, dvhs_score;
  330. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  331. return -1;
  332. score = analyze(buf, size, TS_PACKET_SIZE, NULL);
  333. dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  334. fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  335. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  336. if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  337. else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  338. else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  339. else return -1;
  340. }
  341. typedef struct SectionHeader {
  342. uint8_t tid;
  343. uint16_t id;
  344. uint8_t version;
  345. uint8_t sec_num;
  346. uint8_t last_sec_num;
  347. } SectionHeader;
  348. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  349. {
  350. const uint8_t *p;
  351. int c;
  352. p = *pp;
  353. if (p >= p_end)
  354. return -1;
  355. c = *p++;
  356. *pp = p;
  357. return c;
  358. }
  359. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  360. {
  361. const uint8_t *p;
  362. int c;
  363. p = *pp;
  364. if ((p + 1) >= p_end)
  365. return -1;
  366. c = AV_RB16(p);
  367. p += 2;
  368. *pp = p;
  369. return c;
  370. }
  371. /* read and allocate a DVB string preceeded by its length */
  372. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  373. {
  374. int len;
  375. const uint8_t *p;
  376. char *str;
  377. p = *pp;
  378. len = get8(&p, p_end);
  379. if (len < 0)
  380. return NULL;
  381. if ((p + len) > p_end)
  382. return NULL;
  383. str = av_malloc(len + 1);
  384. if (!str)
  385. return NULL;
  386. memcpy(str, p, len);
  387. str[len] = '\0';
  388. p += len;
  389. *pp = p;
  390. return str;
  391. }
  392. static int parse_section_header(SectionHeader *h,
  393. const uint8_t **pp, const uint8_t *p_end)
  394. {
  395. int val;
  396. val = get8(pp, p_end);
  397. if (val < 0)
  398. return -1;
  399. h->tid = val;
  400. *pp += 2;
  401. val = get16(pp, p_end);
  402. if (val < 0)
  403. return -1;
  404. h->id = val;
  405. val = get8(pp, p_end);
  406. if (val < 0)
  407. return -1;
  408. h->version = (val >> 1) & 0x1f;
  409. val = get8(pp, p_end);
  410. if (val < 0)
  411. return -1;
  412. h->sec_num = val;
  413. val = get8(pp, p_end);
  414. if (val < 0)
  415. return -1;
  416. h->last_sec_num = val;
  417. return 0;
  418. }
  419. typedef struct {
  420. uint32_t stream_type;
  421. enum AVMediaType codec_type;
  422. enum CodecID codec_id;
  423. } StreamType;
  424. static const StreamType ISO_types[] = {
  425. { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  426. { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  427. { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
  428. { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
  429. { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
  430. { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
  431. //{ 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC }, /* LATM syntax */
  432. { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
  433. { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
  434. { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
  435. { 0 },
  436. };
  437. static const StreamType HDMV_types[] = {
  438. { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
  439. { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  440. { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  441. { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
  442. { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
  443. { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
  444. { 0 },
  445. };
  446. /* ATSC ? */
  447. static const StreamType MISC_types[] = {
  448. { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  449. { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  450. { 0 },
  451. };
  452. static const StreamType REGD_types[] = {
  453. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
  454. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  455. { 0 },
  456. };
  457. /* descriptor present */
  458. static const StreamType DESC_types[] = {
  459. { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
  460. { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  461. { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  462. { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
  463. { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  464. { 0 },
  465. };
  466. static void mpegts_find_stream_type(AVStream *st,
  467. uint32_t stream_type, const StreamType *types)
  468. {
  469. for (; types->stream_type; types++) {
  470. if (stream_type == types->stream_type) {
  471. st->codec->codec_type = types->codec_type;
  472. st->codec->codec_id = types->codec_id;
  473. return;
  474. }
  475. }
  476. }
  477. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  478. uint32_t stream_type, uint32_t prog_reg_desc)
  479. {
  480. av_set_pts_info(st, 33, 1, 90000);
  481. st->priv_data = pes;
  482. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  483. st->codec->codec_id = CODEC_ID_NONE;
  484. st->need_parsing = AVSTREAM_PARSE_FULL;
  485. pes->st = st;
  486. pes->stream_type = stream_type;
  487. av_log(pes->stream, AV_LOG_DEBUG,
  488. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  489. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  490. st->codec->codec_tag = pes->stream_type;
  491. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  492. if (prog_reg_desc == AV_RL32("HDMV") &&
  493. st->codec->codec_id == CODEC_ID_NONE) {
  494. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  495. if (pes->stream_type == 0x83) {
  496. // HDMV TrueHD streams also contain an AC3 coded version of the
  497. // audio track - add a second stream for this
  498. AVStream *sub_st;
  499. // priv_data cannot be shared between streams
  500. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  501. if (!sub_pes)
  502. return AVERROR(ENOMEM);
  503. memcpy(sub_pes, pes, sizeof(*sub_pes));
  504. sub_st = av_new_stream(pes->stream, pes->pid);
  505. if (!sub_st) {
  506. av_free(sub_pes);
  507. return AVERROR(ENOMEM);
  508. }
  509. av_set_pts_info(sub_st, 33, 1, 90000);
  510. sub_st->priv_data = sub_pes;
  511. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  512. sub_st->codec->codec_id = CODEC_ID_AC3;
  513. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  514. sub_pes->sub_st = pes->sub_st = sub_st;
  515. }
  516. }
  517. if (pes->stream_type == 0x11)
  518. av_log(pes->stream, AV_LOG_WARNING,
  519. "AAC LATM not currently supported, patch welcome\n");
  520. if (st->codec->codec_id == CODEC_ID_NONE)
  521. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  522. return 0;
  523. }
  524. static int64_t get_pts(const uint8_t *p)
  525. {
  526. int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
  527. pts |= (AV_RB16(p + 1) >> 1) << 15;
  528. pts |= AV_RB16(p + 3) >> 1;
  529. return pts;
  530. }
  531. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  532. {
  533. av_init_packet(pkt);
  534. pkt->destruct = av_destruct_packet;
  535. pkt->data = pes->buffer;
  536. pkt->size = pes->data_index;
  537. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  538. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  539. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  540. pkt->stream_index = pes->sub_st->index;
  541. else
  542. pkt->stream_index = pes->st->index;
  543. pkt->pts = pes->pts;
  544. pkt->dts = pes->dts;
  545. /* store position of first TS packet of this PES packet */
  546. pkt->pos = pes->ts_packet_pos;
  547. /* reset pts values */
  548. pes->pts = AV_NOPTS_VALUE;
  549. pes->dts = AV_NOPTS_VALUE;
  550. pes->buffer = NULL;
  551. pes->data_index = 0;
  552. }
  553. /* return non zero if a packet could be constructed */
  554. static int mpegts_push_data(MpegTSFilter *filter,
  555. const uint8_t *buf, int buf_size, int is_start,
  556. int64_t pos)
  557. {
  558. PESContext *pes = filter->u.pes_filter.opaque;
  559. MpegTSContext *ts = pes->ts;
  560. const uint8_t *p;
  561. int len, code;
  562. if(!ts->pkt)
  563. return 0;
  564. if (is_start) {
  565. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  566. new_pes_packet(pes, ts->pkt);
  567. ts->stop_parse = 1;
  568. }
  569. pes->state = MPEGTS_HEADER;
  570. pes->data_index = 0;
  571. pes->ts_packet_pos = pos;
  572. }
  573. p = buf;
  574. while (buf_size > 0) {
  575. switch(pes->state) {
  576. case MPEGTS_HEADER:
  577. len = PES_START_SIZE - pes->data_index;
  578. if (len > buf_size)
  579. len = buf_size;
  580. memcpy(pes->header + pes->data_index, p, len);
  581. pes->data_index += len;
  582. p += len;
  583. buf_size -= len;
  584. if (pes->data_index == PES_START_SIZE) {
  585. /* we got all the PES or section header. We can now
  586. decide */
  587. #if 0
  588. av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
  589. #endif
  590. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  591. pes->header[2] == 0x01) {
  592. /* it must be an mpeg2 PES stream */
  593. code = pes->header[3] | 0x100;
  594. dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  595. if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
  596. (pes->st && pes->st->discard == AVDISCARD_ALL) ||
  597. code == 0x1be) /* padding_stream */
  598. goto skip;
  599. /* stream not present in PMT */
  600. if (!pes->st) {
  601. pes->st = av_new_stream(ts->stream, pes->pid);
  602. if (!pes->st)
  603. return AVERROR(ENOMEM);
  604. mpegts_set_stream_info(pes->st, pes, 0, 0);
  605. }
  606. pes->total_size = AV_RB16(pes->header + 4);
  607. /* NOTE: a zero total size means the PES size is
  608. unbounded */
  609. if (!pes->total_size)
  610. pes->total_size = MAX_PES_PAYLOAD;
  611. /* allocate pes buffer */
  612. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  613. if (!pes->buffer)
  614. return AVERROR(ENOMEM);
  615. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  616. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  617. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  618. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  619. pes->state = MPEGTS_PESHEADER;
  620. if (pes->st->codec->codec_id == CODEC_ID_NONE) {
  621. dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
  622. pes->pid, pes->stream_type);
  623. pes->st->codec->codec_id = CODEC_ID_PROBE;
  624. }
  625. } else {
  626. pes->state = MPEGTS_PAYLOAD;
  627. pes->data_index = 0;
  628. }
  629. } else {
  630. /* otherwise, it should be a table */
  631. /* skip packet */
  632. skip:
  633. pes->state = MPEGTS_SKIP;
  634. continue;
  635. }
  636. }
  637. break;
  638. /**********************************************/
  639. /* PES packing parsing */
  640. case MPEGTS_PESHEADER:
  641. len = PES_HEADER_SIZE - pes->data_index;
  642. if (len < 0)
  643. return -1;
  644. if (len > buf_size)
  645. len = buf_size;
  646. memcpy(pes->header + pes->data_index, p, len);
  647. pes->data_index += len;
  648. p += len;
  649. buf_size -= len;
  650. if (pes->data_index == PES_HEADER_SIZE) {
  651. pes->pes_header_size = pes->header[8] + 9;
  652. pes->state = MPEGTS_PESHEADER_FILL;
  653. }
  654. break;
  655. case MPEGTS_PESHEADER_FILL:
  656. len = pes->pes_header_size - pes->data_index;
  657. if (len < 0)
  658. return -1;
  659. if (len > buf_size)
  660. len = buf_size;
  661. memcpy(pes->header + pes->data_index, p, len);
  662. pes->data_index += len;
  663. p += len;
  664. buf_size -= len;
  665. if (pes->data_index == pes->pes_header_size) {
  666. const uint8_t *r;
  667. unsigned int flags, pes_ext, skip;
  668. flags = pes->header[7];
  669. r = pes->header + 9;
  670. pes->pts = AV_NOPTS_VALUE;
  671. pes->dts = AV_NOPTS_VALUE;
  672. if ((flags & 0xc0) == 0x80) {
  673. pes->dts = pes->pts = get_pts(r);
  674. r += 5;
  675. } else if ((flags & 0xc0) == 0xc0) {
  676. pes->pts = get_pts(r);
  677. r += 5;
  678. pes->dts = get_pts(r);
  679. r += 5;
  680. }
  681. pes->extended_stream_id = -1;
  682. if (flags & 0x01) { /* PES extension */
  683. pes_ext = *r++;
  684. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  685. skip = (pes_ext >> 4) & 0xb;
  686. skip += skip & 0x9;
  687. r += skip;
  688. if ((pes_ext & 0x41) == 0x01 &&
  689. (r + 2) <= (pes->header + pes->pes_header_size)) {
  690. /* PES extension 2 */
  691. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  692. pes->extended_stream_id = r[1];
  693. }
  694. }
  695. /* we got the full header. We parse it and get the payload */
  696. pes->state = MPEGTS_PAYLOAD;
  697. pes->data_index = 0;
  698. }
  699. break;
  700. case MPEGTS_PAYLOAD:
  701. if (buf_size > 0 && pes->buffer) {
  702. if (pes->data_index+buf_size > pes->total_size) {
  703. new_pes_packet(pes, ts->pkt);
  704. pes->total_size = MAX_PES_PAYLOAD;
  705. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  706. if (!pes->buffer)
  707. return AVERROR(ENOMEM);
  708. ts->stop_parse = 1;
  709. }
  710. memcpy(pes->buffer+pes->data_index, p, buf_size);
  711. pes->data_index += buf_size;
  712. }
  713. buf_size = 0;
  714. /* emit complete packets with known packet size
  715. * decreases demuxer delay for infrequent packets like subtitles from
  716. * a couple of seconds to milliseconds for properly muxed files.
  717. * total_size is the number of bytes following pes_packet_length
  718. * in the pes header, i.e. not counting the first 6 bytes */
  719. if (pes->total_size < MAX_PES_PAYLOAD &&
  720. pes->pes_header_size + pes->data_index == pes->total_size + 6) {
  721. ts->stop_parse = 1;
  722. new_pes_packet(pes, ts->pkt);
  723. }
  724. break;
  725. case MPEGTS_SKIP:
  726. buf_size = 0;
  727. break;
  728. }
  729. }
  730. return 0;
  731. }
  732. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  733. {
  734. MpegTSFilter *tss;
  735. PESContext *pes;
  736. /* if no pid found, then add a pid context */
  737. pes = av_mallocz(sizeof(PESContext));
  738. if (!pes)
  739. return 0;
  740. pes->ts = ts;
  741. pes->stream = ts->stream;
  742. pes->pid = pid;
  743. pes->pcr_pid = pcr_pid;
  744. pes->state = MPEGTS_SKIP;
  745. pes->pts = AV_NOPTS_VALUE;
  746. pes->dts = AV_NOPTS_VALUE;
  747. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  748. if (!tss) {
  749. av_free(pes);
  750. return 0;
  751. }
  752. return pes;
  753. }
  754. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  755. {
  756. MpegTSContext *ts = filter->u.section_filter.opaque;
  757. SectionHeader h1, *h = &h1;
  758. PESContext *pes;
  759. AVStream *st;
  760. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  761. int program_info_length, pcr_pid, pid, stream_type;
  762. int desc_list_len, desc_len, desc_tag;
  763. int comp_page, anc_page;
  764. char language[4];
  765. uint32_t prog_reg_desc = 0; /* registration descriptor */
  766. #ifdef DEBUG
  767. dprintf(ts->stream, "PMT: len %i\n", section_len);
  768. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  769. #endif
  770. p_end = section + section_len - 4;
  771. p = section;
  772. if (parse_section_header(h, &p, p_end) < 0)
  773. return;
  774. dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  775. h->id, h->sec_num, h->last_sec_num);
  776. if (h->tid != PMT_TID)
  777. return;
  778. clear_program(ts, h->id);
  779. pcr_pid = get16(&p, p_end) & 0x1fff;
  780. if (pcr_pid < 0)
  781. return;
  782. add_pid_to_pmt(ts, h->id, pcr_pid);
  783. dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  784. program_info_length = get16(&p, p_end) & 0xfff;
  785. if (program_info_length < 0)
  786. return;
  787. while(program_info_length >= 2) {
  788. uint8_t tag, len;
  789. tag = get8(&p, p_end);
  790. len = get8(&p, p_end);
  791. if(len > program_info_length - 2)
  792. //something else is broken, exit the program_descriptors_loop
  793. break;
  794. program_info_length -= len + 2;
  795. if(tag == 0x05 && len >= 4) { // registration descriptor
  796. prog_reg_desc = bytestream_get_le32(&p);
  797. len -= 4;
  798. }
  799. p += len;
  800. }
  801. p += program_info_length;
  802. if (p >= p_end)
  803. return;
  804. // stop parsing after pmt, we found header
  805. if (!ts->stream->nb_streams)
  806. ts->stop_parse = 1;
  807. for(;;) {
  808. st = 0;
  809. stream_type = get8(&p, p_end);
  810. if (stream_type < 0)
  811. break;
  812. pid = get16(&p, p_end) & 0x1fff;
  813. if (pid < 0)
  814. break;
  815. /* now create ffmpeg stream */
  816. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  817. pes = ts->pids[pid]->u.pes_filter.opaque;
  818. st = pes->st;
  819. } else {
  820. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  821. pes = add_pes_stream(ts, pid, pcr_pid);
  822. if (pes)
  823. st = av_new_stream(pes->stream, pes->pid);
  824. }
  825. if (!st)
  826. return;
  827. if (!pes->stream_type)
  828. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  829. add_pid_to_pmt(ts, h->id, pid);
  830. ff_program_add_stream_index(ts->stream, h->id, st->index);
  831. desc_list_len = get16(&p, p_end) & 0xfff;
  832. if (desc_list_len < 0)
  833. break;
  834. desc_list_end = p + desc_list_len;
  835. if (desc_list_end > p_end)
  836. break;
  837. for(;;) {
  838. desc_tag = get8(&p, desc_list_end);
  839. if (desc_tag < 0)
  840. break;
  841. desc_len = get8(&p, desc_list_end);
  842. if (desc_len < 0)
  843. break;
  844. desc_end = p + desc_len;
  845. if (desc_end > desc_list_end)
  846. break;
  847. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  848. desc_tag, desc_len);
  849. if (st->codec->codec_id == CODEC_ID_NONE &&
  850. stream_type == STREAM_TYPE_PRIVATE_DATA)
  851. mpegts_find_stream_type(st, desc_tag, DESC_types);
  852. switch(desc_tag) {
  853. case 0x56: /* DVB teletext descriptor */
  854. language[0] = get8(&p, desc_end);
  855. language[1] = get8(&p, desc_end);
  856. language[2] = get8(&p, desc_end);
  857. language[3] = 0;
  858. av_metadata_set2(&st->metadata, "language", language, 0);
  859. break;
  860. case 0x59: /* subtitling descriptor */
  861. language[0] = get8(&p, desc_end);
  862. language[1] = get8(&p, desc_end);
  863. language[2] = get8(&p, desc_end);
  864. language[3] = 0;
  865. get8(&p, desc_end);
  866. comp_page = get16(&p, desc_end);
  867. anc_page = get16(&p, desc_end);
  868. st->codec->sub_id = (anc_page << 16) | comp_page;
  869. av_metadata_set2(&st->metadata, "language", language, 0);
  870. break;
  871. case 0x0a: /* ISO 639 language descriptor */
  872. language[0] = get8(&p, desc_end);
  873. language[1] = get8(&p, desc_end);
  874. language[2] = get8(&p, desc_end);
  875. language[3] = 0;
  876. av_metadata_set2(&st->metadata, "language", language, 0);
  877. break;
  878. case 0x05: /* registration descriptor */
  879. st->codec->codec_tag = bytestream_get_le32(&p);
  880. dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  881. if (st->codec->codec_id == CODEC_ID_NONE &&
  882. stream_type == STREAM_TYPE_PRIVATE_DATA)
  883. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  884. break;
  885. default:
  886. break;
  887. }
  888. p = desc_end;
  889. if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  890. ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  891. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  892. }
  893. }
  894. p = desc_list_end;
  895. }
  896. /* all parameters are there */
  897. mpegts_close_filter(ts, filter);
  898. }
  899. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  900. {
  901. MpegTSContext *ts = filter->u.section_filter.opaque;
  902. SectionHeader h1, *h = &h1;
  903. const uint8_t *p, *p_end;
  904. int sid, pmt_pid;
  905. #ifdef DEBUG
  906. dprintf(ts->stream, "PAT:\n");
  907. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  908. #endif
  909. p_end = section + section_len - 4;
  910. p = section;
  911. if (parse_section_header(h, &p, p_end) < 0)
  912. return;
  913. if (h->tid != PAT_TID)
  914. return;
  915. clear_programs(ts);
  916. for(;;) {
  917. sid = get16(&p, p_end);
  918. if (sid < 0)
  919. break;
  920. pmt_pid = get16(&p, p_end) & 0x1fff;
  921. if (pmt_pid < 0)
  922. break;
  923. dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  924. if (sid == 0x0000) {
  925. /* NIT info */
  926. } else {
  927. av_new_program(ts->stream, sid);
  928. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  929. add_pat_entry(ts, sid);
  930. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  931. add_pid_to_pmt(ts, sid, pmt_pid);
  932. }
  933. }
  934. }
  935. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  936. {
  937. MpegTSContext *ts = filter->u.section_filter.opaque;
  938. SectionHeader h1, *h = &h1;
  939. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  940. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  941. char *name, *provider_name;
  942. #ifdef DEBUG
  943. dprintf(ts->stream, "SDT:\n");
  944. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  945. #endif
  946. p_end = section + section_len - 4;
  947. p = section;
  948. if (parse_section_header(h, &p, p_end) < 0)
  949. return;
  950. if (h->tid != SDT_TID)
  951. return;
  952. onid = get16(&p, p_end);
  953. if (onid < 0)
  954. return;
  955. val = get8(&p, p_end);
  956. if (val < 0)
  957. return;
  958. for(;;) {
  959. sid = get16(&p, p_end);
  960. if (sid < 0)
  961. break;
  962. val = get8(&p, p_end);
  963. if (val < 0)
  964. break;
  965. desc_list_len = get16(&p, p_end) & 0xfff;
  966. if (desc_list_len < 0)
  967. break;
  968. desc_list_end = p + desc_list_len;
  969. if (desc_list_end > p_end)
  970. break;
  971. for(;;) {
  972. desc_tag = get8(&p, desc_list_end);
  973. if (desc_tag < 0)
  974. break;
  975. desc_len = get8(&p, desc_list_end);
  976. desc_end = p + desc_len;
  977. if (desc_end > desc_list_end)
  978. break;
  979. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  980. desc_tag, desc_len);
  981. switch(desc_tag) {
  982. case 0x48:
  983. service_type = get8(&p, p_end);
  984. if (service_type < 0)
  985. break;
  986. provider_name = getstr8(&p, p_end);
  987. if (!provider_name)
  988. break;
  989. name = getstr8(&p, p_end);
  990. if (name) {
  991. AVProgram *program = av_new_program(ts->stream, sid);
  992. if(program) {
  993. av_metadata_set2(&program->metadata, "name", name, 0);
  994. av_metadata_set2(&program->metadata, "provider_name", provider_name, 0);
  995. }
  996. }
  997. av_free(name);
  998. av_free(provider_name);
  999. break;
  1000. default:
  1001. break;
  1002. }
  1003. p = desc_end;
  1004. }
  1005. p = desc_list_end;
  1006. }
  1007. }
  1008. /* handle one TS packet */
  1009. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1010. {
  1011. AVFormatContext *s = ts->stream;
  1012. MpegTSFilter *tss;
  1013. int len, pid, cc, cc_ok, afc, is_start;
  1014. const uint8_t *p, *p_end;
  1015. int64_t pos;
  1016. pid = AV_RB16(packet + 1) & 0x1fff;
  1017. if(pid && discard_pid(ts, pid))
  1018. return 0;
  1019. is_start = packet[1] & 0x40;
  1020. tss = ts->pids[pid];
  1021. if (ts->auto_guess && tss == NULL && is_start) {
  1022. add_pes_stream(ts, pid, -1);
  1023. tss = ts->pids[pid];
  1024. }
  1025. if (!tss)
  1026. return 0;
  1027. /* continuity check (currently not used) */
  1028. cc = (packet[3] & 0xf);
  1029. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  1030. tss->last_cc = cc;
  1031. /* skip adaptation field */
  1032. afc = (packet[3] >> 4) & 3;
  1033. p = packet + 4;
  1034. if (afc == 0) /* reserved value */
  1035. return 0;
  1036. if (afc == 2) /* adaptation field only */
  1037. return 0;
  1038. if (afc == 3) {
  1039. /* skip adapation field */
  1040. p += p[0] + 1;
  1041. }
  1042. /* if past the end of packet, ignore */
  1043. p_end = packet + TS_PACKET_SIZE;
  1044. if (p >= p_end)
  1045. return 0;
  1046. pos = url_ftell(ts->stream->pb);
  1047. ts->pos47= pos % ts->raw_packet_size;
  1048. if (tss->type == MPEGTS_SECTION) {
  1049. if (is_start) {
  1050. /* pointer field present */
  1051. len = *p++;
  1052. if (p + len > p_end)
  1053. return 0;
  1054. if (len && cc_ok) {
  1055. /* write remaining section bytes */
  1056. write_section_data(s, tss,
  1057. p, len, 0);
  1058. /* check whether filter has been closed */
  1059. if (!ts->pids[pid])
  1060. return 0;
  1061. }
  1062. p += len;
  1063. if (p < p_end) {
  1064. write_section_data(s, tss,
  1065. p, p_end - p, 1);
  1066. }
  1067. } else {
  1068. if (cc_ok) {
  1069. write_section_data(s, tss,
  1070. p, p_end - p, 0);
  1071. }
  1072. }
  1073. } else {
  1074. int ret;
  1075. // Note: The position here points actually behind the current packet.
  1076. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1077. pos - ts->raw_packet_size)) < 0)
  1078. return ret;
  1079. }
  1080. return 0;
  1081. }
  1082. /* XXX: try to find a better synchro over several packets (use
  1083. get_packet_size() ?) */
  1084. static int mpegts_resync(AVFormatContext *s)
  1085. {
  1086. ByteIOContext *pb = s->pb;
  1087. int c, i;
  1088. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1089. c = url_fgetc(pb);
  1090. if (c < 0)
  1091. return -1;
  1092. if (c == 0x47) {
  1093. url_fseek(pb, -1, SEEK_CUR);
  1094. return 0;
  1095. }
  1096. }
  1097. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1098. /* no sync found */
  1099. return -1;
  1100. }
  1101. /* return -1 if error or EOF. Return 0 if OK. */
  1102. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1103. {
  1104. ByteIOContext *pb = s->pb;
  1105. int skip, len;
  1106. for(;;) {
  1107. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  1108. if (len != TS_PACKET_SIZE)
  1109. return AVERROR(EIO);
  1110. /* check paquet sync byte */
  1111. if (buf[0] != 0x47) {
  1112. /* find a new packet start */
  1113. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1114. if (mpegts_resync(s) < 0)
  1115. return AVERROR(EAGAIN);
  1116. else
  1117. continue;
  1118. } else {
  1119. skip = raw_packet_size - TS_PACKET_SIZE;
  1120. if (skip > 0)
  1121. url_fskip(pb, skip);
  1122. break;
  1123. }
  1124. }
  1125. return 0;
  1126. }
  1127. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1128. {
  1129. AVFormatContext *s = ts->stream;
  1130. uint8_t packet[TS_PACKET_SIZE];
  1131. int packet_num, ret;
  1132. ts->stop_parse = 0;
  1133. packet_num = 0;
  1134. for(;;) {
  1135. if (ts->stop_parse>0)
  1136. break;
  1137. packet_num++;
  1138. if (nb_packets != 0 && packet_num >= nb_packets)
  1139. break;
  1140. ret = read_packet(s, packet, ts->raw_packet_size);
  1141. if (ret != 0)
  1142. return ret;
  1143. ret = handle_packet(ts, packet);
  1144. if (ret != 0)
  1145. return ret;
  1146. }
  1147. return 0;
  1148. }
  1149. static int mpegts_probe(AVProbeData *p)
  1150. {
  1151. #if 1
  1152. const int size= p->buf_size;
  1153. int score, fec_score, dvhs_score;
  1154. int check_count= size / TS_FEC_PACKET_SIZE;
  1155. #define CHECK_COUNT 10
  1156. if (check_count < CHECK_COUNT)
  1157. return -1;
  1158. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1159. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1160. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1161. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1162. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1163. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1164. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1165. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1166. else return -1;
  1167. #else
  1168. /* only use the extension for safer guess */
  1169. if (av_match_ext(p->filename, "ts"))
  1170. return AVPROBE_SCORE_MAX;
  1171. else
  1172. return 0;
  1173. #endif
  1174. }
  1175. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1176. (-1) if not available */
  1177. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1178. const uint8_t *packet)
  1179. {
  1180. int afc, len, flags;
  1181. const uint8_t *p;
  1182. unsigned int v;
  1183. afc = (packet[3] >> 4) & 3;
  1184. if (afc <= 1)
  1185. return -1;
  1186. p = packet + 4;
  1187. len = p[0];
  1188. p++;
  1189. if (len == 0)
  1190. return -1;
  1191. flags = *p++;
  1192. len--;
  1193. if (!(flags & 0x10))
  1194. return -1;
  1195. if (len < 6)
  1196. return -1;
  1197. v = AV_RB32(p);
  1198. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1199. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1200. return 0;
  1201. }
  1202. static int mpegts_read_header(AVFormatContext *s,
  1203. AVFormatParameters *ap)
  1204. {
  1205. MpegTSContext *ts = s->priv_data;
  1206. ByteIOContext *pb = s->pb;
  1207. uint8_t buf[5*1024];
  1208. int len;
  1209. int64_t pos;
  1210. if (ap) {
  1211. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1212. if(ap->mpeg2ts_raw){
  1213. av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
  1214. return -1;
  1215. }
  1216. }
  1217. /* read the first 1024 bytes to get packet size */
  1218. pos = url_ftell(pb);
  1219. len = get_buffer(pb, buf, sizeof(buf));
  1220. if (len != sizeof(buf))
  1221. goto fail;
  1222. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1223. if (ts->raw_packet_size <= 0)
  1224. goto fail;
  1225. ts->stream = s;
  1226. ts->auto_guess = 0;
  1227. if (s->iformat == &mpegts_demuxer) {
  1228. /* normal demux */
  1229. /* first do a scaning to get all the services */
  1230. url_fseek(pb, pos, SEEK_SET);
  1231. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1232. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1233. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1234. /* if could not find service, enable auto_guess */
  1235. ts->auto_guess = 1;
  1236. dprintf(ts->stream, "tuning done\n");
  1237. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1238. } else {
  1239. AVStream *st;
  1240. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1241. int64_t pcrs[2], pcr_h;
  1242. int packet_count[2];
  1243. uint8_t packet[TS_PACKET_SIZE];
  1244. /* only read packets */
  1245. st = av_new_stream(s, 0);
  1246. if (!st)
  1247. goto fail;
  1248. av_set_pts_info(st, 60, 1, 27000000);
  1249. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1250. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1251. /* we iterate until we find two PCRs to estimate the bitrate */
  1252. pcr_pid = -1;
  1253. nb_pcrs = 0;
  1254. nb_packets = 0;
  1255. for(;;) {
  1256. ret = read_packet(s, packet, ts->raw_packet_size);
  1257. if (ret < 0)
  1258. return -1;
  1259. pid = AV_RB16(packet + 1) & 0x1fff;
  1260. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1261. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1262. pcr_pid = pid;
  1263. packet_count[nb_pcrs] = nb_packets;
  1264. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1265. nb_pcrs++;
  1266. if (nb_pcrs >= 2)
  1267. break;
  1268. }
  1269. nb_packets++;
  1270. }
  1271. /* NOTE1: the bitrate is computed without the FEC */
  1272. /* NOTE2: it is only the bitrate of the start of the stream */
  1273. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1274. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1275. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1276. st->codec->bit_rate = s->bit_rate;
  1277. st->start_time = ts->cur_pcr;
  1278. #if 0
  1279. av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
  1280. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1281. #endif
  1282. }
  1283. url_fseek(pb, pos, SEEK_SET);
  1284. return 0;
  1285. fail:
  1286. return -1;
  1287. }
  1288. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1289. static int mpegts_raw_read_packet(AVFormatContext *s,
  1290. AVPacket *pkt)
  1291. {
  1292. MpegTSContext *ts = s->priv_data;
  1293. int ret, i;
  1294. int64_t pcr_h, next_pcr_h, pos;
  1295. int pcr_l, next_pcr_l;
  1296. uint8_t pcr_buf[12];
  1297. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1298. return AVERROR(ENOMEM);
  1299. pkt->pos= url_ftell(s->pb);
  1300. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1301. if (ret < 0) {
  1302. av_free_packet(pkt);
  1303. return ret;
  1304. }
  1305. if (ts->mpeg2ts_compute_pcr) {
  1306. /* compute exact PCR for each packet */
  1307. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1308. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1309. pos = url_ftell(s->pb);
  1310. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1311. url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1312. get_buffer(s->pb, pcr_buf, 12);
  1313. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1314. /* XXX: not precise enough */
  1315. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1316. (i + 1);
  1317. break;
  1318. }
  1319. }
  1320. url_fseek(s->pb, pos, SEEK_SET);
  1321. /* no next PCR found: we use previous increment */
  1322. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1323. }
  1324. pkt->pts = ts->cur_pcr;
  1325. pkt->duration = ts->pcr_incr;
  1326. ts->cur_pcr += ts->pcr_incr;
  1327. }
  1328. pkt->stream_index = 0;
  1329. return 0;
  1330. }
  1331. static int mpegts_read_packet(AVFormatContext *s,
  1332. AVPacket *pkt)
  1333. {
  1334. MpegTSContext *ts = s->priv_data;
  1335. int ret, i;
  1336. if (url_ftell(s->pb) != ts->last_pos) {
  1337. /* seek detected, flush pes buffer */
  1338. for (i = 0; i < NB_PID_MAX; i++) {
  1339. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1340. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1341. av_freep(&pes->buffer);
  1342. pes->data_index = 0;
  1343. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1344. }
  1345. }
  1346. }
  1347. ts->pkt = pkt;
  1348. ret = handle_packets(ts, 0);
  1349. if (ret < 0) {
  1350. /* flush pes data left */
  1351. for (i = 0; i < NB_PID_MAX; i++) {
  1352. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1353. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1354. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1355. new_pes_packet(pes, pkt);
  1356. pes->state = MPEGTS_SKIP;
  1357. ret = 0;
  1358. break;
  1359. }
  1360. }
  1361. }
  1362. }
  1363. ts->last_pos = url_ftell(s->pb);
  1364. return ret;
  1365. }
  1366. static int mpegts_read_close(AVFormatContext *s)
  1367. {
  1368. MpegTSContext *ts = s->priv_data;
  1369. int i;
  1370. clear_programs(ts);
  1371. for(i=0;i<NB_PID_MAX;i++)
  1372. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1373. return 0;
  1374. }
  1375. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1376. int64_t *ppos, int64_t pos_limit)
  1377. {
  1378. MpegTSContext *ts = s->priv_data;
  1379. int64_t pos, timestamp;
  1380. uint8_t buf[TS_PACKET_SIZE];
  1381. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1382. const int find_next= 1;
  1383. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1384. if (find_next) {
  1385. for(;;) {
  1386. url_fseek(s->pb, pos, SEEK_SET);
  1387. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1388. return AV_NOPTS_VALUE;
  1389. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1390. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1391. break;
  1392. }
  1393. pos += ts->raw_packet_size;
  1394. }
  1395. } else {
  1396. for(;;) {
  1397. pos -= ts->raw_packet_size;
  1398. if (pos < 0)
  1399. return AV_NOPTS_VALUE;
  1400. url_fseek(s->pb, pos, SEEK_SET);
  1401. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1402. return AV_NOPTS_VALUE;
  1403. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1404. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1405. break;
  1406. }
  1407. }
  1408. }
  1409. *ppos = pos;
  1410. return timestamp;
  1411. }
  1412. #ifdef USE_SYNCPOINT_SEARCH
  1413. static int read_seek2(AVFormatContext *s,
  1414. int stream_index,
  1415. int64_t min_ts,
  1416. int64_t target_ts,
  1417. int64_t max_ts,
  1418. int flags)
  1419. {
  1420. int64_t pos;
  1421. int64_t ts_ret, ts_adj;
  1422. int stream_index_gen_search;
  1423. AVStream *st;
  1424. AVParserState *backup;
  1425. backup = ff_store_parser_state(s);
  1426. // detect direction of seeking for search purposes
  1427. flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
  1428. AVSEEK_FLAG_BACKWARD : 0;
  1429. if (flags & AVSEEK_FLAG_BYTE) {
  1430. // use position directly, we will search starting from it
  1431. pos = target_ts;
  1432. } else {
  1433. // search for some position with good timestamp match
  1434. if (stream_index < 0) {
  1435. stream_index_gen_search = av_find_default_stream_index(s);
  1436. if (stream_index_gen_search < 0) {
  1437. ff_restore_parser_state(s, backup);
  1438. return -1;
  1439. }
  1440. st = s->streams[stream_index_gen_search];
  1441. // timestamp for default must be expressed in AV_TIME_BASE units
  1442. ts_adj = av_rescale(target_ts,
  1443. st->time_base.den,
  1444. AV_TIME_BASE * (int64_t)st->time_base.num);
  1445. } else {
  1446. ts_adj = target_ts;
  1447. stream_index_gen_search = stream_index;
  1448. }
  1449. pos = av_gen_search(s, stream_index_gen_search, ts_adj,
  1450. 0, INT64_MAX, -1,
  1451. AV_NOPTS_VALUE,
  1452. AV_NOPTS_VALUE,
  1453. flags, &ts_ret, mpegts_get_pcr);
  1454. if (pos < 0) {
  1455. ff_restore_parser_state(s, backup);
  1456. return -1;
  1457. }
  1458. }
  1459. // search for actual matching keyframe/starting position for all streams
  1460. if (ff_gen_syncpoint_search(s, stream_index, pos,
  1461. min_ts, target_ts, max_ts,
  1462. flags) < 0) {
  1463. ff_restore_parser_state(s, backup);
  1464. return -1;
  1465. }
  1466. ff_free_parser_state(s, backup);
  1467. return 0;
  1468. }
  1469. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
  1470. {
  1471. int ret;
  1472. if (flags & AVSEEK_FLAG_BACKWARD) {
  1473. flags &= ~AVSEEK_FLAG_BACKWARD;
  1474. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
  1475. if (ret < 0)
  1476. // for compatibility reasons, seek to the best-fitting timestamp
  1477. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1478. } else {
  1479. ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
  1480. if (ret < 0)
  1481. // for compatibility reasons, seek to the best-fitting timestamp
  1482. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1483. }
  1484. return ret;
  1485. }
  1486. #else
  1487. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1488. MpegTSContext *ts = s->priv_data;
  1489. uint8_t buf[TS_PACKET_SIZE];
  1490. int64_t pos;
  1491. if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1492. return -1;
  1493. pos= url_ftell(s->pb);
  1494. for(;;) {
  1495. url_fseek(s->pb, pos, SEEK_SET);
  1496. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1497. return -1;
  1498. // pid = AV_RB16(buf + 1) & 0x1fff;
  1499. if(buf[1] & 0x40) break;
  1500. pos += ts->raw_packet_size;
  1501. }
  1502. url_fseek(s->pb, pos, SEEK_SET);
  1503. return 0;
  1504. }
  1505. #endif
  1506. /**************************************************************/
  1507. /* parsing functions - called from other demuxers such as RTP */
  1508. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1509. {
  1510. MpegTSContext *ts;
  1511. ts = av_mallocz(sizeof(MpegTSContext));
  1512. if (!ts)
  1513. return NULL;
  1514. /* no stream case, currently used by RTP */
  1515. ts->raw_packet_size = TS_PACKET_SIZE;
  1516. ts->stream = s;
  1517. ts->auto_guess = 1;
  1518. return ts;
  1519. }
  1520. /* return the consumed length if a packet was output, or -1 if no
  1521. packet is output */
  1522. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1523. const uint8_t *buf, int len)
  1524. {
  1525. int len1;
  1526. len1 = len;
  1527. ts->pkt = pkt;
  1528. ts->stop_parse = 0;
  1529. for(;;) {
  1530. if (ts->stop_parse>0)
  1531. break;
  1532. if (len < TS_PACKET_SIZE)
  1533. return -1;
  1534. if (buf[0] != 0x47) {
  1535. buf++;
  1536. len--;
  1537. } else {
  1538. handle_packet(ts, buf);
  1539. buf += TS_PACKET_SIZE;
  1540. len -= TS_PACKET_SIZE;
  1541. }
  1542. }
  1543. return len1 - len;
  1544. }
  1545. void ff_mpegts_parse_close(MpegTSContext *ts)
  1546. {
  1547. int i;
  1548. for(i=0;i<NB_PID_MAX;i++)
  1549. av_free(ts->pids[i]);
  1550. av_free(ts);
  1551. }
  1552. AVInputFormat mpegts_demuxer = {
  1553. "mpegts",
  1554. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1555. sizeof(MpegTSContext),
  1556. mpegts_probe,
  1557. mpegts_read_header,
  1558. mpegts_read_packet,
  1559. mpegts_read_close,
  1560. read_seek,
  1561. mpegts_get_pcr,
  1562. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1563. #ifdef USE_SYNCPOINT_SEARCH
  1564. .read_seek2 = read_seek2,
  1565. #endif
  1566. };
  1567. AVInputFormat mpegtsraw_demuxer = {
  1568. "mpegtsraw",
  1569. NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1570. sizeof(MpegTSContext),
  1571. NULL,
  1572. mpegts_read_header,
  1573. mpegts_raw_read_packet,
  1574. mpegts_read_close,
  1575. read_seek,
  1576. mpegts_get_pcr,
  1577. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1578. #ifdef USE_SYNCPOINT_SEARCH
  1579. .read_seek2 = read_seek2,
  1580. #endif
  1581. };