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.

1619 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_PROBE;
  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_PROBE)
  486. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  487. if (st->codec->codec_id == CODEC_ID_PROBE)
  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_PROBE) {
  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. for(;;) {
  552. st = 0;
  553. stream_type = get8(&p, p_end);
  554. if (stream_type < 0)
  555. break;
  556. pid = get16(&p, p_end) & 0x1fff;
  557. if (pid < 0)
  558. break;
  559. /* now create ffmpeg stream */
  560. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  561. pes = ts->pids[pid]->u.pes_filter.opaque;
  562. st = pes->st;
  563. } else {
  564. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  565. pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
  566. if (pes)
  567. st = new_pes_av_stream(pes, prog_reg_desc, 0);
  568. }
  569. if (!st)
  570. return;
  571. add_pid_to_pmt(ts, h->id, pid);
  572. av_program_add_stream_index(ts->stream, h->id, st->index);
  573. desc_list_len = get16(&p, p_end) & 0xfff;
  574. if (desc_list_len < 0)
  575. break;
  576. desc_list_end = p + desc_list_len;
  577. if (desc_list_end > p_end)
  578. break;
  579. for(;;) {
  580. desc_tag = get8(&p, desc_list_end);
  581. if (desc_tag < 0)
  582. break;
  583. desc_len = get8(&p, desc_list_end);
  584. if (desc_len < 0)
  585. break;
  586. desc_end = p + desc_len;
  587. if (desc_end > desc_list_end)
  588. break;
  589. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  590. desc_tag, desc_len);
  591. if (st->codec->codec_id == CODEC_ID_PROBE &&
  592. stream_type == STREAM_TYPE_PRIVATE_DATA)
  593. mpegts_find_stream_type(st, desc_tag, DESC_types);
  594. switch(desc_tag) {
  595. case 0x59: /* subtitling descriptor */
  596. language[0] = get8(&p, desc_end);
  597. language[1] = get8(&p, desc_end);
  598. language[2] = get8(&p, desc_end);
  599. language[3] = 0;
  600. get8(&p, desc_end);
  601. comp_page = get16(&p, desc_end);
  602. anc_page = get16(&p, desc_end);
  603. st->codec->sub_id = (anc_page << 16) | comp_page;
  604. av_metadata_set(&st->metadata, "language", language);
  605. break;
  606. case 0x0a: /* ISO 639 language descriptor */
  607. language[0] = get8(&p, desc_end);
  608. language[1] = get8(&p, desc_end);
  609. language[2] = get8(&p, desc_end);
  610. language[3] = 0;
  611. av_metadata_set(&st->metadata, "language", language);
  612. break;
  613. case 0x05: /* registration descriptor */
  614. st->codec->codec_tag = bytestream_get_le32(&p);
  615. dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  616. if (st->codec->codec_id == CODEC_ID_PROBE &&
  617. stream_type == STREAM_TYPE_PRIVATE_DATA)
  618. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  619. break;
  620. default:
  621. break;
  622. }
  623. p = desc_end;
  624. }
  625. p = desc_list_end;
  626. }
  627. /* all parameters are there */
  628. ts->stop_parse++;
  629. mpegts_close_filter(ts, filter);
  630. }
  631. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  632. {
  633. MpegTSContext *ts = filter->u.section_filter.opaque;
  634. SectionHeader h1, *h = &h1;
  635. const uint8_t *p, *p_end;
  636. int sid, pmt_pid;
  637. #ifdef DEBUG
  638. dprintf(ts->stream, "PAT:\n");
  639. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  640. #endif
  641. p_end = section + section_len - 4;
  642. p = section;
  643. if (parse_section_header(h, &p, p_end) < 0)
  644. return;
  645. if (h->tid != PAT_TID)
  646. return;
  647. clear_programs(ts);
  648. for(;;) {
  649. sid = get16(&p, p_end);
  650. if (sid < 0)
  651. break;
  652. pmt_pid = get16(&p, p_end) & 0x1fff;
  653. if (pmt_pid < 0)
  654. break;
  655. dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  656. if (sid == 0x0000) {
  657. /* NIT info */
  658. } else {
  659. av_new_program(ts->stream, sid);
  660. ts->stop_parse--;
  661. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  662. add_pat_entry(ts, sid);
  663. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  664. add_pid_to_pmt(ts, sid, pmt_pid);
  665. }
  666. }
  667. /* not found */
  668. ts->stop_parse++;
  669. mpegts_close_filter(ts, filter);
  670. }
  671. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  672. {
  673. MpegTSContext *ts = filter->u.section_filter.opaque;
  674. SectionHeader h1, *h = &h1;
  675. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  676. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  677. char *name, *provider_name;
  678. #ifdef DEBUG
  679. dprintf(ts->stream, "SDT:\n");
  680. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  681. #endif
  682. p_end = section + section_len - 4;
  683. p = section;
  684. if (parse_section_header(h, &p, p_end) < 0)
  685. return;
  686. if (h->tid != SDT_TID)
  687. return;
  688. onid = get16(&p, p_end);
  689. if (onid < 0)
  690. return;
  691. val = get8(&p, p_end);
  692. if (val < 0)
  693. return;
  694. for(;;) {
  695. sid = get16(&p, p_end);
  696. if (sid < 0)
  697. break;
  698. val = get8(&p, p_end);
  699. if (val < 0)
  700. break;
  701. desc_list_len = get16(&p, p_end) & 0xfff;
  702. if (desc_list_len < 0)
  703. break;
  704. desc_list_end = p + desc_list_len;
  705. if (desc_list_end > p_end)
  706. break;
  707. for(;;) {
  708. desc_tag = get8(&p, desc_list_end);
  709. if (desc_tag < 0)
  710. break;
  711. desc_len = get8(&p, desc_list_end);
  712. desc_end = p + desc_len;
  713. if (desc_end > desc_list_end)
  714. break;
  715. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  716. desc_tag, desc_len);
  717. switch(desc_tag) {
  718. case 0x48:
  719. service_type = get8(&p, p_end);
  720. if (service_type < 0)
  721. break;
  722. provider_name = getstr8(&p, p_end);
  723. if (!provider_name)
  724. break;
  725. name = getstr8(&p, p_end);
  726. if (name) {
  727. AVProgram *program = av_new_program(ts->stream, sid);
  728. if(program) {
  729. av_metadata_set(&program->metadata, "name", name);
  730. av_metadata_set(&program->metadata, "provider_name", provider_name);
  731. }
  732. }
  733. av_free(name);
  734. av_free(provider_name);
  735. break;
  736. default:
  737. break;
  738. }
  739. p = desc_end;
  740. }
  741. p = desc_list_end;
  742. }
  743. }
  744. static int64_t get_pts(const uint8_t *p)
  745. {
  746. int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
  747. pts |= (AV_RB16(p + 1) >> 1) << 15;
  748. pts |= AV_RB16(p + 3) >> 1;
  749. return pts;
  750. }
  751. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  752. {
  753. av_init_packet(pkt);
  754. pkt->destruct = av_destruct_packet;
  755. pkt->data = pes->buffer;
  756. pkt->size = pes->data_index;
  757. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  758. pkt->stream_index = pes->st->index;
  759. pkt->pts = pes->pts;
  760. pkt->dts = pes->dts;
  761. /* store position of first TS packet of this PES packet */
  762. pkt->pos = pes->ts_packet_pos;
  763. /* reset pts values */
  764. pes->pts = AV_NOPTS_VALUE;
  765. pes->dts = AV_NOPTS_VALUE;
  766. pes->buffer = NULL;
  767. pes->data_index = 0;
  768. }
  769. /* return non zero if a packet could be constructed */
  770. static int mpegts_push_data(MpegTSFilter *filter,
  771. const uint8_t *buf, int buf_size, int is_start,
  772. int64_t pos)
  773. {
  774. PESContext *pes = filter->u.pes_filter.opaque;
  775. MpegTSContext *ts = pes->ts;
  776. const uint8_t *p;
  777. int len, code;
  778. if(!ts->pkt)
  779. return 0;
  780. if (is_start) {
  781. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  782. new_pes_packet(pes, ts->pkt);
  783. ts->stop_parse = 1;
  784. }
  785. pes->state = MPEGTS_HEADER;
  786. pes->data_index = 0;
  787. pes->ts_packet_pos = pos;
  788. }
  789. p = buf;
  790. while (buf_size > 0) {
  791. switch(pes->state) {
  792. case MPEGTS_HEADER:
  793. len = PES_START_SIZE - pes->data_index;
  794. if (len > buf_size)
  795. len = buf_size;
  796. memcpy(pes->header + pes->data_index, p, len);
  797. pes->data_index += len;
  798. p += len;
  799. buf_size -= len;
  800. if (pes->data_index == PES_START_SIZE) {
  801. /* we got all the PES or section header. We can now
  802. decide */
  803. #if 0
  804. av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
  805. #endif
  806. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  807. pes->header[2] == 0x01) {
  808. /* it must be an mpeg2 PES stream */
  809. code = pes->header[3] | 0x100;
  810. dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  811. if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
  812. (pes->st && pes->st->discard == AVDISCARD_ALL) ||
  813. code == 0x1be) /* padding_stream */
  814. goto skip;
  815. /* stream not present in PMT */
  816. if (!pes->st)
  817. pes->st = new_pes_av_stream(pes, 0, code);
  818. if (!pes->st)
  819. return AVERROR(ENOMEM);
  820. pes->total_size = AV_RB16(pes->header + 4);
  821. /* NOTE: a zero total size means the PES size is
  822. unbounded */
  823. if (!pes->total_size)
  824. pes->total_size = MAX_PES_PAYLOAD;
  825. /* allocate pes buffer */
  826. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  827. if (!pes->buffer)
  828. return AVERROR(ENOMEM);
  829. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  830. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  831. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  832. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  833. pes->state = MPEGTS_PESHEADER;
  834. } else {
  835. pes->state = MPEGTS_PAYLOAD;
  836. pes->data_index = 0;
  837. }
  838. } else {
  839. /* otherwise, it should be a table */
  840. /* skip packet */
  841. skip:
  842. pes->state = MPEGTS_SKIP;
  843. continue;
  844. }
  845. }
  846. break;
  847. /**********************************************/
  848. /* PES packing parsing */
  849. case MPEGTS_PESHEADER:
  850. len = PES_HEADER_SIZE - pes->data_index;
  851. if (len < 0)
  852. return -1;
  853. if (len > buf_size)
  854. len = buf_size;
  855. memcpy(pes->header + pes->data_index, p, len);
  856. pes->data_index += len;
  857. p += len;
  858. buf_size -= len;
  859. if (pes->data_index == PES_HEADER_SIZE) {
  860. pes->pes_header_size = pes->header[8] + 9;
  861. pes->state = MPEGTS_PESHEADER_FILL;
  862. }
  863. break;
  864. case MPEGTS_PESHEADER_FILL:
  865. len = pes->pes_header_size - pes->data_index;
  866. if (len < 0)
  867. return -1;
  868. if (len > buf_size)
  869. len = buf_size;
  870. memcpy(pes->header + pes->data_index, p, len);
  871. pes->data_index += len;
  872. p += len;
  873. buf_size -= len;
  874. if (pes->data_index == pes->pes_header_size) {
  875. const uint8_t *r;
  876. unsigned int flags;
  877. flags = pes->header[7];
  878. r = pes->header + 9;
  879. pes->pts = AV_NOPTS_VALUE;
  880. pes->dts = AV_NOPTS_VALUE;
  881. if ((flags & 0xc0) == 0x80) {
  882. pes->dts = pes->pts = get_pts(r);
  883. r += 5;
  884. } else if ((flags & 0xc0) == 0xc0) {
  885. pes->pts = get_pts(r);
  886. r += 5;
  887. pes->dts = get_pts(r);
  888. r += 5;
  889. }
  890. /* we got the full header. We parse it and get the payload */
  891. pes->state = MPEGTS_PAYLOAD;
  892. pes->data_index = 0;
  893. }
  894. break;
  895. case MPEGTS_PAYLOAD:
  896. if (buf_size > 0) {
  897. if (pes->data_index+buf_size > pes->total_size) {
  898. new_pes_packet(pes, ts->pkt);
  899. pes->total_size = MAX_PES_PAYLOAD;
  900. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  901. if (!pes->buffer)
  902. return AVERROR(ENOMEM);
  903. ts->stop_parse = 1;
  904. }
  905. memcpy(pes->buffer+pes->data_index, p, buf_size);
  906. pes->data_index += buf_size;
  907. }
  908. buf_size = 0;
  909. break;
  910. case MPEGTS_SKIP:
  911. buf_size = 0;
  912. break;
  913. }
  914. }
  915. return 0;
  916. }
  917. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
  918. {
  919. MpegTSFilter *tss;
  920. PESContext *pes;
  921. /* if no pid found, then add a pid context */
  922. pes = av_mallocz(sizeof(PESContext));
  923. if (!pes)
  924. return 0;
  925. pes->ts = ts;
  926. pes->stream = ts->stream;
  927. pes->pid = pid;
  928. pes->pcr_pid = pcr_pid;
  929. pes->stream_type = stream_type;
  930. pes->state = MPEGTS_SKIP;
  931. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  932. if (!tss) {
  933. av_free(pes);
  934. return 0;
  935. }
  936. return pes;
  937. }
  938. /* handle one TS packet */
  939. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  940. {
  941. AVFormatContext *s = ts->stream;
  942. MpegTSFilter *tss;
  943. int len, pid, cc, cc_ok, afc, is_start;
  944. const uint8_t *p, *p_end;
  945. int64_t pos;
  946. pid = AV_RB16(packet + 1) & 0x1fff;
  947. if(pid && discard_pid(ts, pid))
  948. return 0;
  949. is_start = packet[1] & 0x40;
  950. tss = ts->pids[pid];
  951. if (ts->auto_guess && tss == NULL && is_start) {
  952. add_pes_stream(ts, pid, -1, 0);
  953. tss = ts->pids[pid];
  954. }
  955. if (!tss)
  956. return 0;
  957. /* continuity check (currently not used) */
  958. cc = (packet[3] & 0xf);
  959. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  960. tss->last_cc = cc;
  961. /* skip adaptation field */
  962. afc = (packet[3] >> 4) & 3;
  963. p = packet + 4;
  964. if (afc == 0) /* reserved value */
  965. return 0;
  966. if (afc == 2) /* adaptation field only */
  967. return 0;
  968. if (afc == 3) {
  969. /* skip adapation field */
  970. p += p[0] + 1;
  971. }
  972. /* if past the end of packet, ignore */
  973. p_end = packet + TS_PACKET_SIZE;
  974. if (p >= p_end)
  975. return 0;
  976. pos = url_ftell(ts->stream->pb);
  977. ts->pos47= pos % ts->raw_packet_size;
  978. if (tss->type == MPEGTS_SECTION) {
  979. if (is_start) {
  980. /* pointer field present */
  981. len = *p++;
  982. if (p + len > p_end)
  983. return 0;
  984. if (len && cc_ok) {
  985. /* write remaining section bytes */
  986. write_section_data(s, tss,
  987. p, len, 0);
  988. /* check whether filter has been closed */
  989. if (!ts->pids[pid])
  990. return 0;
  991. }
  992. p += len;
  993. if (p < p_end) {
  994. write_section_data(s, tss,
  995. p, p_end - p, 1);
  996. }
  997. } else {
  998. if (cc_ok) {
  999. write_section_data(s, tss,
  1000. p, p_end - p, 0);
  1001. }
  1002. }
  1003. } else {
  1004. int ret;
  1005. // Note: The position here points actually behind the current packet.
  1006. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1007. pos - ts->raw_packet_size)) < 0)
  1008. return ret;
  1009. }
  1010. return 0;
  1011. }
  1012. /* XXX: try to find a better synchro over several packets (use
  1013. get_packet_size() ?) */
  1014. static int mpegts_resync(ByteIOContext *pb)
  1015. {
  1016. int c, i;
  1017. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1018. c = url_fgetc(pb);
  1019. if (c < 0)
  1020. return -1;
  1021. if (c == 0x47) {
  1022. url_fseek(pb, -1, SEEK_CUR);
  1023. return 0;
  1024. }
  1025. }
  1026. /* no sync found */
  1027. return -1;
  1028. }
  1029. /* return -1 if error or EOF. Return 0 if OK. */
  1030. static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
  1031. {
  1032. int skip, len;
  1033. for(;;) {
  1034. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  1035. if (len != TS_PACKET_SIZE)
  1036. return AVERROR(EIO);
  1037. /* check paquet sync byte */
  1038. if (buf[0] != 0x47) {
  1039. /* find a new packet start */
  1040. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1041. if (mpegts_resync(pb) < 0)
  1042. return AVERROR_INVALIDDATA;
  1043. else
  1044. continue;
  1045. } else {
  1046. skip = raw_packet_size - TS_PACKET_SIZE;
  1047. if (skip > 0)
  1048. url_fskip(pb, skip);
  1049. break;
  1050. }
  1051. }
  1052. return 0;
  1053. }
  1054. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1055. {
  1056. AVFormatContext *s = ts->stream;
  1057. ByteIOContext *pb = s->pb;
  1058. uint8_t packet[TS_PACKET_SIZE];
  1059. int packet_num, ret;
  1060. ts->stop_parse = 0;
  1061. packet_num = 0;
  1062. for(;;) {
  1063. if (ts->stop_parse>0)
  1064. break;
  1065. packet_num++;
  1066. if (nb_packets != 0 && packet_num >= nb_packets)
  1067. break;
  1068. ret = read_packet(pb, packet, ts->raw_packet_size);
  1069. if (ret != 0)
  1070. return ret;
  1071. ret = handle_packet(ts, packet);
  1072. if (ret != 0)
  1073. return ret;
  1074. }
  1075. return 0;
  1076. }
  1077. static int mpegts_probe(AVProbeData *p)
  1078. {
  1079. #if 1
  1080. const int size= p->buf_size;
  1081. int score, fec_score, dvhs_score;
  1082. int check_count= size / TS_FEC_PACKET_SIZE;
  1083. #define CHECK_COUNT 10
  1084. if (check_count < CHECK_COUNT)
  1085. return -1;
  1086. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1087. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1088. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1089. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1090. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1091. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1092. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1093. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1094. else return -1;
  1095. #else
  1096. /* only use the extension for safer guess */
  1097. if (match_ext(p->filename, "ts"))
  1098. return AVPROBE_SCORE_MAX;
  1099. else
  1100. return 0;
  1101. #endif
  1102. }
  1103. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1104. (-1) if not available */
  1105. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1106. const uint8_t *packet)
  1107. {
  1108. int afc, len, flags;
  1109. const uint8_t *p;
  1110. unsigned int v;
  1111. afc = (packet[3] >> 4) & 3;
  1112. if (afc <= 1)
  1113. return -1;
  1114. p = packet + 4;
  1115. len = p[0];
  1116. p++;
  1117. if (len == 0)
  1118. return -1;
  1119. flags = *p++;
  1120. len--;
  1121. if (!(flags & 0x10))
  1122. return -1;
  1123. if (len < 6)
  1124. return -1;
  1125. v = AV_RB32(p);
  1126. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1127. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1128. return 0;
  1129. }
  1130. static int mpegts_read_header(AVFormatContext *s,
  1131. AVFormatParameters *ap)
  1132. {
  1133. MpegTSContext *ts = s->priv_data;
  1134. ByteIOContext *pb = s->pb;
  1135. uint8_t buf[5*1024];
  1136. int len;
  1137. int64_t pos;
  1138. if (ap) {
  1139. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1140. if(ap->mpeg2ts_raw){
  1141. av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
  1142. return -1;
  1143. }
  1144. }
  1145. /* read the first 1024 bytes to get packet size */
  1146. pos = url_ftell(pb);
  1147. len = get_buffer(pb, buf, sizeof(buf));
  1148. if (len != sizeof(buf))
  1149. goto fail;
  1150. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1151. if (ts->raw_packet_size <= 0)
  1152. goto fail;
  1153. ts->stream = s;
  1154. ts->auto_guess = 0;
  1155. if (s->iformat == &mpegts_demuxer) {
  1156. /* normal demux */
  1157. /* first do a scaning to get all the services */
  1158. url_fseek(pb, pos, SEEK_SET);
  1159. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1160. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1161. handle_packets(ts, s->probesize);
  1162. /* if could not find service, enable auto_guess */
  1163. ts->auto_guess = 1;
  1164. dprintf(ts->stream, "tuning done\n");
  1165. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1166. } else {
  1167. AVStream *st;
  1168. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1169. int64_t pcrs[2], pcr_h;
  1170. int packet_count[2];
  1171. uint8_t packet[TS_PACKET_SIZE];
  1172. /* only read packets */
  1173. st = av_new_stream(s, 0);
  1174. if (!st)
  1175. goto fail;
  1176. av_set_pts_info(st, 60, 1, 27000000);
  1177. st->codec->codec_type = CODEC_TYPE_DATA;
  1178. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1179. /* we iterate until we find two PCRs to estimate the bitrate */
  1180. pcr_pid = -1;
  1181. nb_pcrs = 0;
  1182. nb_packets = 0;
  1183. for(;;) {
  1184. ret = read_packet(s->pb, packet, ts->raw_packet_size);
  1185. if (ret < 0)
  1186. return -1;
  1187. pid = AV_RB16(packet + 1) & 0x1fff;
  1188. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1189. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1190. pcr_pid = pid;
  1191. packet_count[nb_pcrs] = nb_packets;
  1192. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1193. nb_pcrs++;
  1194. if (nb_pcrs >= 2)
  1195. break;
  1196. }
  1197. nb_packets++;
  1198. }
  1199. /* NOTE1: the bitrate is computed without the FEC */
  1200. /* NOTE2: it is only the bitrate of the start of the stream */
  1201. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1202. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1203. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1204. st->codec->bit_rate = s->bit_rate;
  1205. st->start_time = ts->cur_pcr;
  1206. #if 0
  1207. av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
  1208. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1209. #endif
  1210. }
  1211. url_fseek(pb, pos, SEEK_SET);
  1212. return 0;
  1213. fail:
  1214. return -1;
  1215. }
  1216. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1217. static int mpegts_raw_read_packet(AVFormatContext *s,
  1218. AVPacket *pkt)
  1219. {
  1220. MpegTSContext *ts = s->priv_data;
  1221. int ret, i;
  1222. int64_t pcr_h, next_pcr_h, pos;
  1223. int pcr_l, next_pcr_l;
  1224. uint8_t pcr_buf[12];
  1225. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1226. return AVERROR(ENOMEM);
  1227. pkt->pos= url_ftell(s->pb);
  1228. ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
  1229. if (ret < 0) {
  1230. av_free_packet(pkt);
  1231. return ret;
  1232. }
  1233. if (ts->mpeg2ts_compute_pcr) {
  1234. /* compute exact PCR for each packet */
  1235. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1236. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1237. pos = url_ftell(s->pb);
  1238. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1239. url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1240. get_buffer(s->pb, pcr_buf, 12);
  1241. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1242. /* XXX: not precise enough */
  1243. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1244. (i + 1);
  1245. break;
  1246. }
  1247. }
  1248. url_fseek(s->pb, pos, SEEK_SET);
  1249. /* no next PCR found: we use previous increment */
  1250. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1251. }
  1252. pkt->pts = ts->cur_pcr;
  1253. pkt->duration = ts->pcr_incr;
  1254. ts->cur_pcr += ts->pcr_incr;
  1255. }
  1256. pkt->stream_index = 0;
  1257. return 0;
  1258. }
  1259. static int mpegts_read_packet(AVFormatContext *s,
  1260. AVPacket *pkt)
  1261. {
  1262. MpegTSContext *ts = s->priv_data;
  1263. int ret, i;
  1264. if (url_ftell(s->pb) != ts->last_pos) {
  1265. /* seek detected, flush pes buffer */
  1266. for (i = 0; i < NB_PID_MAX; i++) {
  1267. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1268. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1269. av_freep(&pes->buffer);
  1270. pes->data_index = 0;
  1271. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1272. }
  1273. }
  1274. }
  1275. ts->pkt = pkt;
  1276. ret = handle_packets(ts, 0);
  1277. if (ret < 0) {
  1278. /* flush pes data left */
  1279. for (i = 0; i < NB_PID_MAX; i++) {
  1280. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1281. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1282. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1283. new_pes_packet(pes, pkt);
  1284. ret = 0;
  1285. break;
  1286. }
  1287. }
  1288. }
  1289. }
  1290. ts->last_pos = url_ftell(s->pb);
  1291. return ret;
  1292. }
  1293. static int mpegts_read_close(AVFormatContext *s)
  1294. {
  1295. MpegTSContext *ts = s->priv_data;
  1296. int i;
  1297. clear_programs(ts);
  1298. for(i=0;i<NB_PID_MAX;i++)
  1299. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1300. return 0;
  1301. }
  1302. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1303. int64_t *ppos, int64_t pos_limit)
  1304. {
  1305. MpegTSContext *ts = s->priv_data;
  1306. int64_t pos, timestamp;
  1307. uint8_t buf[TS_PACKET_SIZE];
  1308. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1309. const int find_next= 1;
  1310. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1311. if (find_next) {
  1312. for(;;) {
  1313. url_fseek(s->pb, pos, SEEK_SET);
  1314. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1315. return AV_NOPTS_VALUE;
  1316. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1317. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1318. break;
  1319. }
  1320. pos += ts->raw_packet_size;
  1321. }
  1322. } else {
  1323. for(;;) {
  1324. pos -= ts->raw_packet_size;
  1325. if (pos < 0)
  1326. return AV_NOPTS_VALUE;
  1327. url_fseek(s->pb, pos, SEEK_SET);
  1328. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1329. return AV_NOPTS_VALUE;
  1330. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1331. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1332. break;
  1333. }
  1334. }
  1335. }
  1336. *ppos = pos;
  1337. return timestamp;
  1338. }
  1339. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1340. MpegTSContext *ts = s->priv_data;
  1341. uint8_t buf[TS_PACKET_SIZE];
  1342. int64_t pos;
  1343. if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1344. return -1;
  1345. pos= url_ftell(s->pb);
  1346. for(;;) {
  1347. url_fseek(s->pb, pos, SEEK_SET);
  1348. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1349. return -1;
  1350. // pid = AV_RB16(buf + 1) & 0x1fff;
  1351. if(buf[1] & 0x40) break;
  1352. pos += ts->raw_packet_size;
  1353. }
  1354. url_fseek(s->pb, pos, SEEK_SET);
  1355. return 0;
  1356. }
  1357. /**************************************************************/
  1358. /* parsing functions - called from other demuxers such as RTP */
  1359. MpegTSContext *mpegts_parse_open(AVFormatContext *s)
  1360. {
  1361. MpegTSContext *ts;
  1362. ts = av_mallocz(sizeof(MpegTSContext));
  1363. if (!ts)
  1364. return NULL;
  1365. /* no stream case, currently used by RTP */
  1366. ts->raw_packet_size = TS_PACKET_SIZE;
  1367. ts->stream = s;
  1368. ts->auto_guess = 1;
  1369. return ts;
  1370. }
  1371. /* return the consumed length if a packet was output, or -1 if no
  1372. packet is output */
  1373. int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1374. const uint8_t *buf, int len)
  1375. {
  1376. int len1;
  1377. len1 = len;
  1378. ts->pkt = pkt;
  1379. ts->stop_parse = 0;
  1380. for(;;) {
  1381. if (ts->stop_parse>0)
  1382. break;
  1383. if (len < TS_PACKET_SIZE)
  1384. return -1;
  1385. if (buf[0] != 0x47) {
  1386. buf++;
  1387. len--;
  1388. } else {
  1389. handle_packet(ts, buf);
  1390. buf += TS_PACKET_SIZE;
  1391. len -= TS_PACKET_SIZE;
  1392. }
  1393. }
  1394. return len1 - len;
  1395. }
  1396. void mpegts_parse_close(MpegTSContext *ts)
  1397. {
  1398. int i;
  1399. for(i=0;i<NB_PID_MAX;i++)
  1400. av_free(ts->pids[i]);
  1401. av_free(ts);
  1402. }
  1403. AVInputFormat mpegts_demuxer = {
  1404. "mpegts",
  1405. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1406. sizeof(MpegTSContext),
  1407. mpegts_probe,
  1408. mpegts_read_header,
  1409. mpegts_read_packet,
  1410. mpegts_read_close,
  1411. read_seek,
  1412. mpegts_get_pcr,
  1413. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1414. };
  1415. AVInputFormat mpegtsraw_demuxer = {
  1416. "mpegtsraw",
  1417. NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1418. sizeof(MpegTSContext),
  1419. NULL,
  1420. mpegts_read_header,
  1421. mpegts_raw_read_packet,
  1422. mpegts_read_close,
  1423. read_seek,
  1424. mpegts_get_pcr,
  1425. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1426. };