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.

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