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.

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