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.

1558 lines
45KB

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