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.

1724 lines
51KB

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