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.

1798 lines
55KB

  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->st->discard == AVDISCARD_ALL) ||
  596. code == 0x1be) /* padding_stream */
  597. goto skip;
  598. #if FF_API_MAX_STREAMS
  599. if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
  600. goto skip;
  601. #endif
  602. /* stream not present in PMT */
  603. if (!pes->st) {
  604. pes->st = av_new_stream(ts->stream, pes->pid);
  605. if (!pes->st)
  606. return AVERROR(ENOMEM);
  607. mpegts_set_stream_info(pes->st, pes, 0, 0);
  608. }
  609. pes->total_size = AV_RB16(pes->header + 4);
  610. /* NOTE: a zero total size means the PES size is
  611. unbounded */
  612. if (!pes->total_size)
  613. pes->total_size = MAX_PES_PAYLOAD;
  614. /* allocate pes buffer */
  615. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  616. if (!pes->buffer)
  617. return AVERROR(ENOMEM);
  618. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  619. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  620. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  621. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  622. pes->state = MPEGTS_PESHEADER;
  623. if (pes->st->codec->codec_id == CODEC_ID_NONE) {
  624. dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
  625. pes->pid, pes->stream_type);
  626. pes->st->codec->codec_id = CODEC_ID_PROBE;
  627. }
  628. } else {
  629. pes->state = MPEGTS_PAYLOAD;
  630. pes->data_index = 0;
  631. }
  632. } else {
  633. /* otherwise, it should be a table */
  634. /* skip packet */
  635. skip:
  636. pes->state = MPEGTS_SKIP;
  637. continue;
  638. }
  639. }
  640. break;
  641. /**********************************************/
  642. /* PES packing parsing */
  643. case MPEGTS_PESHEADER:
  644. len = PES_HEADER_SIZE - pes->data_index;
  645. if (len < 0)
  646. return -1;
  647. if (len > buf_size)
  648. len = buf_size;
  649. memcpy(pes->header + pes->data_index, p, len);
  650. pes->data_index += len;
  651. p += len;
  652. buf_size -= len;
  653. if (pes->data_index == PES_HEADER_SIZE) {
  654. pes->pes_header_size = pes->header[8] + 9;
  655. pes->state = MPEGTS_PESHEADER_FILL;
  656. }
  657. break;
  658. case MPEGTS_PESHEADER_FILL:
  659. len = pes->pes_header_size - pes->data_index;
  660. if (len < 0)
  661. return -1;
  662. if (len > buf_size)
  663. len = buf_size;
  664. memcpy(pes->header + pes->data_index, p, len);
  665. pes->data_index += len;
  666. p += len;
  667. buf_size -= len;
  668. if (pes->data_index == pes->pes_header_size) {
  669. const uint8_t *r;
  670. unsigned int flags, pes_ext, skip;
  671. flags = pes->header[7];
  672. r = pes->header + 9;
  673. pes->pts = AV_NOPTS_VALUE;
  674. pes->dts = AV_NOPTS_VALUE;
  675. if ((flags & 0xc0) == 0x80) {
  676. pes->dts = pes->pts = get_pts(r);
  677. r += 5;
  678. } else if ((flags & 0xc0) == 0xc0) {
  679. pes->pts = get_pts(r);
  680. r += 5;
  681. pes->dts = get_pts(r);
  682. r += 5;
  683. }
  684. pes->extended_stream_id = -1;
  685. if (flags & 0x01) { /* PES extension */
  686. pes_ext = *r++;
  687. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  688. skip = (pes_ext >> 4) & 0xb;
  689. skip += skip & 0x9;
  690. r += skip;
  691. if ((pes_ext & 0x41) == 0x01 &&
  692. (r + 2) <= (pes->header + pes->pes_header_size)) {
  693. /* PES extension 2 */
  694. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  695. pes->extended_stream_id = r[1];
  696. }
  697. }
  698. /* we got the full header. We parse it and get the payload */
  699. pes->state = MPEGTS_PAYLOAD;
  700. pes->data_index = 0;
  701. }
  702. break;
  703. case MPEGTS_PAYLOAD:
  704. if (buf_size > 0 && pes->buffer) {
  705. if (pes->data_index+buf_size > pes->total_size) {
  706. new_pes_packet(pes, ts->pkt);
  707. pes->total_size = MAX_PES_PAYLOAD;
  708. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  709. if (!pes->buffer)
  710. return AVERROR(ENOMEM);
  711. ts->stop_parse = 1;
  712. }
  713. memcpy(pes->buffer+pes->data_index, p, buf_size);
  714. pes->data_index += buf_size;
  715. }
  716. buf_size = 0;
  717. /* emit complete packets with known packet size
  718. * decreases demuxer delay for infrequent packets like subtitles from
  719. * a couple of seconds to milliseconds for properly muxed files.
  720. * total_size is the number of bytes following pes_packet_length
  721. * in the pes header, i.e. not counting the first 6 bytes */
  722. if (pes->total_size < MAX_PES_PAYLOAD &&
  723. pes->pes_header_size + pes->data_index == pes->total_size + 6) {
  724. ts->stop_parse = 1;
  725. new_pes_packet(pes, ts->pkt);
  726. }
  727. break;
  728. case MPEGTS_SKIP:
  729. buf_size = 0;
  730. break;
  731. }
  732. }
  733. return 0;
  734. }
  735. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  736. {
  737. MpegTSFilter *tss;
  738. PESContext *pes;
  739. /* if no pid found, then add a pid context */
  740. pes = av_mallocz(sizeof(PESContext));
  741. if (!pes)
  742. return 0;
  743. pes->ts = ts;
  744. pes->stream = ts->stream;
  745. pes->pid = pid;
  746. pes->pcr_pid = pcr_pid;
  747. pes->state = MPEGTS_SKIP;
  748. pes->pts = AV_NOPTS_VALUE;
  749. pes->dts = AV_NOPTS_VALUE;
  750. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  751. if (!tss) {
  752. av_free(pes);
  753. return 0;
  754. }
  755. return pes;
  756. }
  757. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  758. {
  759. MpegTSContext *ts = filter->u.section_filter.opaque;
  760. SectionHeader h1, *h = &h1;
  761. PESContext *pes;
  762. AVStream *st;
  763. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  764. int program_info_length, pcr_pid, pid, stream_type;
  765. int desc_list_len, desc_len, desc_tag;
  766. char language[4];
  767. uint32_t prog_reg_desc = 0; /* registration descriptor */
  768. #ifdef DEBUG
  769. dprintf(ts->stream, "PMT: len %i\n", section_len);
  770. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  771. #endif
  772. p_end = section + section_len - 4;
  773. p = section;
  774. if (parse_section_header(h, &p, p_end) < 0)
  775. return;
  776. dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  777. h->id, h->sec_num, h->last_sec_num);
  778. if (h->tid != PMT_TID)
  779. return;
  780. clear_program(ts, h->id);
  781. pcr_pid = get16(&p, p_end) & 0x1fff;
  782. if (pcr_pid < 0)
  783. return;
  784. add_pid_to_pmt(ts, h->id, pcr_pid);
  785. dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  786. program_info_length = get16(&p, p_end) & 0xfff;
  787. if (program_info_length < 0)
  788. return;
  789. while(program_info_length >= 2) {
  790. uint8_t tag, len;
  791. tag = get8(&p, p_end);
  792. len = get8(&p, p_end);
  793. if(len > program_info_length - 2)
  794. //something else is broken, exit the program_descriptors_loop
  795. break;
  796. program_info_length -= len + 2;
  797. if(tag == 0x05 && len >= 4) { // registration descriptor
  798. prog_reg_desc = bytestream_get_le32(&p);
  799. len -= 4;
  800. }
  801. p += len;
  802. }
  803. p += program_info_length;
  804. if (p >= p_end)
  805. return;
  806. // stop parsing after pmt, we found header
  807. if (!ts->stream->nb_streams)
  808. ts->stop_parse = 1;
  809. for(;;) {
  810. st = 0;
  811. stream_type = get8(&p, p_end);
  812. if (stream_type < 0)
  813. break;
  814. pid = get16(&p, p_end) & 0x1fff;
  815. if (pid < 0)
  816. break;
  817. /* now create ffmpeg stream */
  818. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  819. pes = ts->pids[pid]->u.pes_filter.opaque;
  820. st = pes->st;
  821. } else {
  822. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  823. pes = add_pes_stream(ts, pid, pcr_pid);
  824. if (pes)
  825. st = av_new_stream(pes->stream, pes->pid);
  826. }
  827. if (!st)
  828. return;
  829. if (!pes->stream_type)
  830. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  831. add_pid_to_pmt(ts, h->id, pid);
  832. ff_program_add_stream_index(ts->stream, h->id, st->index);
  833. desc_list_len = get16(&p, p_end) & 0xfff;
  834. if (desc_list_len < 0)
  835. break;
  836. desc_list_end = p + desc_list_len;
  837. if (desc_list_end > p_end)
  838. break;
  839. for(;;) {
  840. desc_tag = get8(&p, desc_list_end);
  841. if (desc_tag < 0)
  842. break;
  843. desc_len = get8(&p, desc_list_end);
  844. if (desc_len < 0)
  845. break;
  846. desc_end = p + desc_len;
  847. if (desc_end > desc_list_end)
  848. break;
  849. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  850. desc_tag, desc_len);
  851. if (st->codec->codec_id == CODEC_ID_NONE &&
  852. stream_type == STREAM_TYPE_PRIVATE_DATA)
  853. mpegts_find_stream_type(st, desc_tag, DESC_types);
  854. switch(desc_tag) {
  855. case 0x56: /* DVB teletext descriptor */
  856. language[0] = get8(&p, desc_end);
  857. language[1] = get8(&p, desc_end);
  858. language[2] = get8(&p, desc_end);
  859. language[3] = 0;
  860. av_metadata_set2(&st->metadata, "language", language, 0);
  861. break;
  862. case 0x59: /* subtitling descriptor */
  863. language[0] = get8(&p, desc_end);
  864. language[1] = get8(&p, desc_end);
  865. language[2] = get8(&p, desc_end);
  866. language[3] = 0;
  867. get8(&p, desc_end);
  868. if (st->codec->extradata) {
  869. if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, p, 4))
  870. av_log_ask_for_sample(ts->stream, "DVB sub with multiple IDs\n");
  871. } else {
  872. st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
  873. if (st->codec->extradata) {
  874. st->codec->extradata_size = 4;
  875. memcpy(st->codec->extradata, p, 4);
  876. }
  877. }
  878. p += 4;
  879. av_metadata_set2(&st->metadata, "language", language, 0);
  880. break;
  881. case 0x0a: /* ISO 639 language descriptor */
  882. language[0] = get8(&p, desc_end);
  883. language[1] = get8(&p, desc_end);
  884. language[2] = get8(&p, desc_end);
  885. language[3] = 0;
  886. av_metadata_set2(&st->metadata, "language", language, 0);
  887. break;
  888. case 0x05: /* registration descriptor */
  889. st->codec->codec_tag = bytestream_get_le32(&p);
  890. dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  891. if (st->codec->codec_id == CODEC_ID_NONE &&
  892. stream_type == STREAM_TYPE_PRIVATE_DATA)
  893. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  894. break;
  895. default:
  896. break;
  897. }
  898. p = desc_end;
  899. if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  900. ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  901. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  902. }
  903. }
  904. p = desc_list_end;
  905. }
  906. /* all parameters are there */
  907. mpegts_close_filter(ts, filter);
  908. }
  909. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  910. {
  911. MpegTSContext *ts = filter->u.section_filter.opaque;
  912. SectionHeader h1, *h = &h1;
  913. const uint8_t *p, *p_end;
  914. int sid, pmt_pid;
  915. #ifdef DEBUG
  916. dprintf(ts->stream, "PAT:\n");
  917. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  918. #endif
  919. p_end = section + section_len - 4;
  920. p = section;
  921. if (parse_section_header(h, &p, p_end) < 0)
  922. return;
  923. if (h->tid != PAT_TID)
  924. return;
  925. clear_programs(ts);
  926. for(;;) {
  927. sid = get16(&p, p_end);
  928. if (sid < 0)
  929. break;
  930. pmt_pid = get16(&p, p_end) & 0x1fff;
  931. if (pmt_pid < 0)
  932. break;
  933. dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  934. if (sid == 0x0000) {
  935. /* NIT info */
  936. } else {
  937. av_new_program(ts->stream, sid);
  938. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  939. add_pat_entry(ts, sid);
  940. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  941. add_pid_to_pmt(ts, sid, pmt_pid);
  942. }
  943. }
  944. }
  945. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  946. {
  947. MpegTSContext *ts = filter->u.section_filter.opaque;
  948. SectionHeader h1, *h = &h1;
  949. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  950. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  951. char *name, *provider_name;
  952. #ifdef DEBUG
  953. dprintf(ts->stream, "SDT:\n");
  954. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  955. #endif
  956. p_end = section + section_len - 4;
  957. p = section;
  958. if (parse_section_header(h, &p, p_end) < 0)
  959. return;
  960. if (h->tid != SDT_TID)
  961. return;
  962. onid = get16(&p, p_end);
  963. if (onid < 0)
  964. return;
  965. val = get8(&p, p_end);
  966. if (val < 0)
  967. return;
  968. for(;;) {
  969. sid = get16(&p, p_end);
  970. if (sid < 0)
  971. break;
  972. val = get8(&p, p_end);
  973. if (val < 0)
  974. break;
  975. desc_list_len = get16(&p, p_end) & 0xfff;
  976. if (desc_list_len < 0)
  977. break;
  978. desc_list_end = p + desc_list_len;
  979. if (desc_list_end > p_end)
  980. break;
  981. for(;;) {
  982. desc_tag = get8(&p, desc_list_end);
  983. if (desc_tag < 0)
  984. break;
  985. desc_len = get8(&p, desc_list_end);
  986. desc_end = p + desc_len;
  987. if (desc_end > desc_list_end)
  988. break;
  989. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  990. desc_tag, desc_len);
  991. switch(desc_tag) {
  992. case 0x48:
  993. service_type = get8(&p, p_end);
  994. if (service_type < 0)
  995. break;
  996. provider_name = getstr8(&p, p_end);
  997. if (!provider_name)
  998. break;
  999. name = getstr8(&p, p_end);
  1000. if (name) {
  1001. AVProgram *program = av_new_program(ts->stream, sid);
  1002. if(program) {
  1003. av_metadata_set2(&program->metadata, "name", name, 0);
  1004. av_metadata_set2(&program->metadata, "provider_name", provider_name, 0);
  1005. }
  1006. }
  1007. av_free(name);
  1008. av_free(provider_name);
  1009. break;
  1010. default:
  1011. break;
  1012. }
  1013. p = desc_end;
  1014. }
  1015. p = desc_list_end;
  1016. }
  1017. }
  1018. /* handle one TS packet */
  1019. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1020. {
  1021. AVFormatContext *s = ts->stream;
  1022. MpegTSFilter *tss;
  1023. int len, pid, cc, cc_ok, afc, is_start;
  1024. const uint8_t *p, *p_end;
  1025. int64_t pos;
  1026. pid = AV_RB16(packet + 1) & 0x1fff;
  1027. if(pid && discard_pid(ts, pid))
  1028. return 0;
  1029. is_start = packet[1] & 0x40;
  1030. tss = ts->pids[pid];
  1031. if (ts->auto_guess && tss == NULL && is_start) {
  1032. add_pes_stream(ts, pid, -1);
  1033. tss = ts->pids[pid];
  1034. }
  1035. if (!tss)
  1036. return 0;
  1037. /* continuity check (currently not used) */
  1038. cc = (packet[3] & 0xf);
  1039. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  1040. tss->last_cc = cc;
  1041. /* skip adaptation field */
  1042. afc = (packet[3] >> 4) & 3;
  1043. p = packet + 4;
  1044. if (afc == 0) /* reserved value */
  1045. return 0;
  1046. if (afc == 2) /* adaptation field only */
  1047. return 0;
  1048. if (afc == 3) {
  1049. /* skip adapation field */
  1050. p += p[0] + 1;
  1051. }
  1052. /* if past the end of packet, ignore */
  1053. p_end = packet + TS_PACKET_SIZE;
  1054. if (p >= p_end)
  1055. return 0;
  1056. pos = url_ftell(ts->stream->pb);
  1057. ts->pos47= pos % ts->raw_packet_size;
  1058. if (tss->type == MPEGTS_SECTION) {
  1059. if (is_start) {
  1060. /* pointer field present */
  1061. len = *p++;
  1062. if (p + len > p_end)
  1063. return 0;
  1064. if (len && cc_ok) {
  1065. /* write remaining section bytes */
  1066. write_section_data(s, tss,
  1067. p, len, 0);
  1068. /* check whether filter has been closed */
  1069. if (!ts->pids[pid])
  1070. return 0;
  1071. }
  1072. p += len;
  1073. if (p < p_end) {
  1074. write_section_data(s, tss,
  1075. p, p_end - p, 1);
  1076. }
  1077. } else {
  1078. if (cc_ok) {
  1079. write_section_data(s, tss,
  1080. p, p_end - p, 0);
  1081. }
  1082. }
  1083. } else {
  1084. int ret;
  1085. // Note: The position here points actually behind the current packet.
  1086. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1087. pos - ts->raw_packet_size)) < 0)
  1088. return ret;
  1089. }
  1090. return 0;
  1091. }
  1092. /* XXX: try to find a better synchro over several packets (use
  1093. get_packet_size() ?) */
  1094. static int mpegts_resync(AVFormatContext *s)
  1095. {
  1096. ByteIOContext *pb = s->pb;
  1097. int c, i;
  1098. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1099. c = url_fgetc(pb);
  1100. if (c < 0)
  1101. return -1;
  1102. if (c == 0x47) {
  1103. url_fseek(pb, -1, SEEK_CUR);
  1104. return 0;
  1105. }
  1106. }
  1107. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1108. /* no sync found */
  1109. return -1;
  1110. }
  1111. /* return -1 if error or EOF. Return 0 if OK. */
  1112. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1113. {
  1114. ByteIOContext *pb = s->pb;
  1115. int skip, len;
  1116. for(;;) {
  1117. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  1118. if (len != TS_PACKET_SIZE)
  1119. return AVERROR(EIO);
  1120. /* check paquet sync byte */
  1121. if (buf[0] != 0x47) {
  1122. /* find a new packet start */
  1123. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1124. if (mpegts_resync(s) < 0)
  1125. return AVERROR(EAGAIN);
  1126. else
  1127. continue;
  1128. } else {
  1129. skip = raw_packet_size - TS_PACKET_SIZE;
  1130. if (skip > 0)
  1131. url_fskip(pb, skip);
  1132. break;
  1133. }
  1134. }
  1135. return 0;
  1136. }
  1137. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1138. {
  1139. AVFormatContext *s = ts->stream;
  1140. uint8_t packet[TS_PACKET_SIZE];
  1141. int packet_num, ret;
  1142. ts->stop_parse = 0;
  1143. packet_num = 0;
  1144. for(;;) {
  1145. if (ts->stop_parse>0)
  1146. break;
  1147. packet_num++;
  1148. if (nb_packets != 0 && packet_num >= nb_packets)
  1149. break;
  1150. ret = read_packet(s, packet, ts->raw_packet_size);
  1151. if (ret != 0)
  1152. return ret;
  1153. ret = handle_packet(ts, packet);
  1154. if (ret != 0)
  1155. return ret;
  1156. }
  1157. return 0;
  1158. }
  1159. static int mpegts_probe(AVProbeData *p)
  1160. {
  1161. #if 1
  1162. const int size= p->buf_size;
  1163. int score, fec_score, dvhs_score;
  1164. int check_count= size / TS_FEC_PACKET_SIZE;
  1165. #define CHECK_COUNT 10
  1166. if (check_count < CHECK_COUNT)
  1167. return -1;
  1168. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1169. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1170. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1171. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1172. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1173. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1174. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1175. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1176. else return -1;
  1177. #else
  1178. /* only use the extension for safer guess */
  1179. if (av_match_ext(p->filename, "ts"))
  1180. return AVPROBE_SCORE_MAX;
  1181. else
  1182. return 0;
  1183. #endif
  1184. }
  1185. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1186. (-1) if not available */
  1187. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1188. const uint8_t *packet)
  1189. {
  1190. int afc, len, flags;
  1191. const uint8_t *p;
  1192. unsigned int v;
  1193. afc = (packet[3] >> 4) & 3;
  1194. if (afc <= 1)
  1195. return -1;
  1196. p = packet + 4;
  1197. len = p[0];
  1198. p++;
  1199. if (len == 0)
  1200. return -1;
  1201. flags = *p++;
  1202. len--;
  1203. if (!(flags & 0x10))
  1204. return -1;
  1205. if (len < 6)
  1206. return -1;
  1207. v = AV_RB32(p);
  1208. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1209. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1210. return 0;
  1211. }
  1212. static int mpegts_read_header(AVFormatContext *s,
  1213. AVFormatParameters *ap)
  1214. {
  1215. MpegTSContext *ts = s->priv_data;
  1216. ByteIOContext *pb = s->pb;
  1217. uint8_t buf[5*1024];
  1218. int len;
  1219. int64_t pos;
  1220. if (ap) {
  1221. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1222. if(ap->mpeg2ts_raw){
  1223. av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
  1224. return -1;
  1225. }
  1226. }
  1227. /* read the first 1024 bytes to get packet size */
  1228. pos = url_ftell(pb);
  1229. len = get_buffer(pb, buf, sizeof(buf));
  1230. if (len != sizeof(buf))
  1231. goto fail;
  1232. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1233. if (ts->raw_packet_size <= 0)
  1234. goto fail;
  1235. ts->stream = s;
  1236. ts->auto_guess = 0;
  1237. if (s->iformat == &mpegts_demuxer) {
  1238. /* normal demux */
  1239. /* first do a scaning to get all the services */
  1240. if (url_fseek(pb, pos, SEEK_SET) < 0)
  1241. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1242. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1243. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1244. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1245. /* if could not find service, enable auto_guess */
  1246. ts->auto_guess = 1;
  1247. dprintf(ts->stream, "tuning done\n");
  1248. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1249. } else {
  1250. AVStream *st;
  1251. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1252. int64_t pcrs[2], pcr_h;
  1253. int packet_count[2];
  1254. uint8_t packet[TS_PACKET_SIZE];
  1255. /* only read packets */
  1256. st = av_new_stream(s, 0);
  1257. if (!st)
  1258. goto fail;
  1259. av_set_pts_info(st, 60, 1, 27000000);
  1260. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1261. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1262. /* we iterate until we find two PCRs to estimate the bitrate */
  1263. pcr_pid = -1;
  1264. nb_pcrs = 0;
  1265. nb_packets = 0;
  1266. for(;;) {
  1267. ret = read_packet(s, packet, ts->raw_packet_size);
  1268. if (ret < 0)
  1269. return -1;
  1270. pid = AV_RB16(packet + 1) & 0x1fff;
  1271. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1272. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1273. pcr_pid = pid;
  1274. packet_count[nb_pcrs] = nb_packets;
  1275. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1276. nb_pcrs++;
  1277. if (nb_pcrs >= 2)
  1278. break;
  1279. }
  1280. nb_packets++;
  1281. }
  1282. /* NOTE1: the bitrate is computed without the FEC */
  1283. /* NOTE2: it is only the bitrate of the start of the stream */
  1284. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1285. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1286. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1287. st->codec->bit_rate = s->bit_rate;
  1288. st->start_time = ts->cur_pcr;
  1289. #if 0
  1290. av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
  1291. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1292. #endif
  1293. }
  1294. url_fseek(pb, pos, SEEK_SET);
  1295. return 0;
  1296. fail:
  1297. return -1;
  1298. }
  1299. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1300. static int mpegts_raw_read_packet(AVFormatContext *s,
  1301. AVPacket *pkt)
  1302. {
  1303. MpegTSContext *ts = s->priv_data;
  1304. int ret, i;
  1305. int64_t pcr_h, next_pcr_h, pos;
  1306. int pcr_l, next_pcr_l;
  1307. uint8_t pcr_buf[12];
  1308. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1309. return AVERROR(ENOMEM);
  1310. pkt->pos= url_ftell(s->pb);
  1311. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1312. if (ret < 0) {
  1313. av_free_packet(pkt);
  1314. return ret;
  1315. }
  1316. if (ts->mpeg2ts_compute_pcr) {
  1317. /* compute exact PCR for each packet */
  1318. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1319. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1320. pos = url_ftell(s->pb);
  1321. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1322. url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1323. get_buffer(s->pb, pcr_buf, 12);
  1324. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1325. /* XXX: not precise enough */
  1326. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1327. (i + 1);
  1328. break;
  1329. }
  1330. }
  1331. url_fseek(s->pb, pos, SEEK_SET);
  1332. /* no next PCR found: we use previous increment */
  1333. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1334. }
  1335. pkt->pts = ts->cur_pcr;
  1336. pkt->duration = ts->pcr_incr;
  1337. ts->cur_pcr += ts->pcr_incr;
  1338. }
  1339. pkt->stream_index = 0;
  1340. return 0;
  1341. }
  1342. static int mpegts_read_packet(AVFormatContext *s,
  1343. AVPacket *pkt)
  1344. {
  1345. MpegTSContext *ts = s->priv_data;
  1346. int ret, i;
  1347. if (url_ftell(s->pb) != ts->last_pos) {
  1348. /* seek detected, flush pes buffer */
  1349. for (i = 0; i < NB_PID_MAX; i++) {
  1350. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1351. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1352. av_freep(&pes->buffer);
  1353. pes->data_index = 0;
  1354. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1355. }
  1356. }
  1357. }
  1358. ts->pkt = pkt;
  1359. ret = handle_packets(ts, 0);
  1360. if (ret < 0) {
  1361. /* flush pes data left */
  1362. for (i = 0; i < NB_PID_MAX; i++) {
  1363. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1364. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1365. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1366. new_pes_packet(pes, pkt);
  1367. pes->state = MPEGTS_SKIP;
  1368. ret = 0;
  1369. break;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. ts->last_pos = url_ftell(s->pb);
  1375. return ret;
  1376. }
  1377. static int mpegts_read_close(AVFormatContext *s)
  1378. {
  1379. MpegTSContext *ts = s->priv_data;
  1380. int i;
  1381. clear_programs(ts);
  1382. for(i=0;i<NB_PID_MAX;i++)
  1383. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1384. return 0;
  1385. }
  1386. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1387. int64_t *ppos, int64_t pos_limit)
  1388. {
  1389. MpegTSContext *ts = s->priv_data;
  1390. int64_t pos, timestamp;
  1391. uint8_t buf[TS_PACKET_SIZE];
  1392. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1393. const int find_next= 1;
  1394. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1395. if (find_next) {
  1396. for(;;) {
  1397. url_fseek(s->pb, pos, SEEK_SET);
  1398. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1399. return AV_NOPTS_VALUE;
  1400. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1401. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1402. break;
  1403. }
  1404. pos += ts->raw_packet_size;
  1405. }
  1406. } else {
  1407. for(;;) {
  1408. pos -= ts->raw_packet_size;
  1409. if (pos < 0)
  1410. return AV_NOPTS_VALUE;
  1411. url_fseek(s->pb, pos, SEEK_SET);
  1412. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1413. return AV_NOPTS_VALUE;
  1414. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1415. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1416. break;
  1417. }
  1418. }
  1419. }
  1420. *ppos = pos;
  1421. return timestamp;
  1422. }
  1423. #ifdef USE_SYNCPOINT_SEARCH
  1424. static int read_seek2(AVFormatContext *s,
  1425. int stream_index,
  1426. int64_t min_ts,
  1427. int64_t target_ts,
  1428. int64_t max_ts,
  1429. int flags)
  1430. {
  1431. int64_t pos;
  1432. int64_t ts_ret, ts_adj;
  1433. int stream_index_gen_search;
  1434. AVStream *st;
  1435. AVParserState *backup;
  1436. backup = ff_store_parser_state(s);
  1437. // detect direction of seeking for search purposes
  1438. flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
  1439. AVSEEK_FLAG_BACKWARD : 0;
  1440. if (flags & AVSEEK_FLAG_BYTE) {
  1441. // use position directly, we will search starting from it
  1442. pos = target_ts;
  1443. } else {
  1444. // search for some position with good timestamp match
  1445. if (stream_index < 0) {
  1446. stream_index_gen_search = av_find_default_stream_index(s);
  1447. if (stream_index_gen_search < 0) {
  1448. ff_restore_parser_state(s, backup);
  1449. return -1;
  1450. }
  1451. st = s->streams[stream_index_gen_search];
  1452. // timestamp for default must be expressed in AV_TIME_BASE units
  1453. ts_adj = av_rescale(target_ts,
  1454. st->time_base.den,
  1455. AV_TIME_BASE * (int64_t)st->time_base.num);
  1456. } else {
  1457. ts_adj = target_ts;
  1458. stream_index_gen_search = stream_index;
  1459. }
  1460. pos = av_gen_search(s, stream_index_gen_search, ts_adj,
  1461. 0, INT64_MAX, -1,
  1462. AV_NOPTS_VALUE,
  1463. AV_NOPTS_VALUE,
  1464. flags, &ts_ret, mpegts_get_pcr);
  1465. if (pos < 0) {
  1466. ff_restore_parser_state(s, backup);
  1467. return -1;
  1468. }
  1469. }
  1470. // search for actual matching keyframe/starting position for all streams
  1471. if (ff_gen_syncpoint_search(s, stream_index, pos,
  1472. min_ts, target_ts, max_ts,
  1473. flags) < 0) {
  1474. ff_restore_parser_state(s, backup);
  1475. return -1;
  1476. }
  1477. ff_free_parser_state(s, backup);
  1478. return 0;
  1479. }
  1480. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
  1481. {
  1482. int ret;
  1483. if (flags & AVSEEK_FLAG_BACKWARD) {
  1484. flags &= ~AVSEEK_FLAG_BACKWARD;
  1485. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
  1486. if (ret < 0)
  1487. // for compatibility reasons, seek to the best-fitting timestamp
  1488. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1489. } else {
  1490. ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
  1491. if (ret < 0)
  1492. // for compatibility reasons, seek to the best-fitting timestamp
  1493. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1494. }
  1495. return ret;
  1496. }
  1497. #else
  1498. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1499. MpegTSContext *ts = s->priv_data;
  1500. uint8_t buf[TS_PACKET_SIZE];
  1501. int64_t pos;
  1502. if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1503. return -1;
  1504. pos= url_ftell(s->pb);
  1505. for(;;) {
  1506. url_fseek(s->pb, pos, SEEK_SET);
  1507. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1508. return -1;
  1509. // pid = AV_RB16(buf + 1) & 0x1fff;
  1510. if(buf[1] & 0x40) break;
  1511. pos += ts->raw_packet_size;
  1512. }
  1513. url_fseek(s->pb, pos, SEEK_SET);
  1514. return 0;
  1515. }
  1516. #endif
  1517. /**************************************************************/
  1518. /* parsing functions - called from other demuxers such as RTP */
  1519. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1520. {
  1521. MpegTSContext *ts;
  1522. ts = av_mallocz(sizeof(MpegTSContext));
  1523. if (!ts)
  1524. return NULL;
  1525. /* no stream case, currently used by RTP */
  1526. ts->raw_packet_size = TS_PACKET_SIZE;
  1527. ts->stream = s;
  1528. ts->auto_guess = 1;
  1529. return ts;
  1530. }
  1531. /* return the consumed length if a packet was output, or -1 if no
  1532. packet is output */
  1533. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1534. const uint8_t *buf, int len)
  1535. {
  1536. int len1;
  1537. len1 = len;
  1538. ts->pkt = pkt;
  1539. ts->stop_parse = 0;
  1540. for(;;) {
  1541. if (ts->stop_parse>0)
  1542. break;
  1543. if (len < TS_PACKET_SIZE)
  1544. return -1;
  1545. if (buf[0] != 0x47) {
  1546. buf++;
  1547. len--;
  1548. } else {
  1549. handle_packet(ts, buf);
  1550. buf += TS_PACKET_SIZE;
  1551. len -= TS_PACKET_SIZE;
  1552. }
  1553. }
  1554. return len1 - len;
  1555. }
  1556. void ff_mpegts_parse_close(MpegTSContext *ts)
  1557. {
  1558. int i;
  1559. for(i=0;i<NB_PID_MAX;i++)
  1560. av_free(ts->pids[i]);
  1561. av_free(ts);
  1562. }
  1563. AVInputFormat mpegts_demuxer = {
  1564. "mpegts",
  1565. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1566. sizeof(MpegTSContext),
  1567. mpegts_probe,
  1568. mpegts_read_header,
  1569. mpegts_read_packet,
  1570. mpegts_read_close,
  1571. read_seek,
  1572. mpegts_get_pcr,
  1573. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1574. #ifdef USE_SYNCPOINT_SEARCH
  1575. .read_seek2 = read_seek2,
  1576. #endif
  1577. };
  1578. AVInputFormat mpegtsraw_demuxer = {
  1579. "mpegtsraw",
  1580. NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1581. sizeof(MpegTSContext),
  1582. NULL,
  1583. mpegts_read_header,
  1584. mpegts_raw_read_packet,
  1585. mpegts_read_close,
  1586. read_seek,
  1587. mpegts_get_pcr,
  1588. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1589. #ifdef USE_SYNCPOINT_SEARCH
  1590. .read_seek2 = read_seek2,
  1591. #endif
  1592. };