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.

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