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.

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