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.

1689 lines
50KB

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