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.

1593 lines
46KB

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