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.

1773 lines
53KB

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