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.

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