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.

1625 lines
47KB

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