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.

1681 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. { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
  437. { 0x82, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
  438. { 0x90, CODEC_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
  439. { 0 },
  440. };
  441. /* ATSC ? */
  442. static const StreamType MISC_types[] = {
  443. { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
  444. { 0x8a, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
  445. { 0 },
  446. };
  447. static const StreamType REGD_types[] = {
  448. { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
  449. { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
  450. { 0 },
  451. };
  452. /* descriptor present */
  453. static const StreamType DESC_types[] = {
  454. { 0x6a, CODEC_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
  455. { 0x7a, CODEC_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  456. { 0x7b, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
  457. { 0x59, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  458. { 0 },
  459. };
  460. static void mpegts_find_stream_type(AVStream *st,
  461. uint32_t stream_type, const StreamType *types)
  462. {
  463. for (; types->stream_type; types++) {
  464. if (stream_type == types->stream_type) {
  465. st->codec->codec_type = types->codec_type;
  466. st->codec->codec_id = types->codec_id;
  467. return;
  468. }
  469. }
  470. }
  471. static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)
  472. {
  473. AVStream *st = av_new_stream(pes->stream, pes->pid);
  474. if (!st)
  475. return NULL;
  476. av_set_pts_info(st, 33, 1, 90000);
  477. st->priv_data = pes;
  478. st->codec->codec_type = CODEC_TYPE_DATA;
  479. st->codec->codec_id = CODEC_ID_NONE;
  480. st->need_parsing = AVSTREAM_PARSE_FULL;
  481. pes->st = st;
  482. dprintf(pes->stream, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  483. pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  484. st->codec->codec_tag = pes->stream_type;
  485. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  486. if (prog_reg_desc == AV_RL32("HDMV") &&
  487. st->codec->codec_id == CODEC_ID_NONE)
  488. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  489. if (st->codec->codec_id == CODEC_ID_NONE)
  490. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  491. /* stream was not present in PMT, guess based on PES start code */
  492. if (st->codec->codec_id == CODEC_ID_NONE) {
  493. if (code >= 0x1c0 && code <= 0x1df) {
  494. st->codec->codec_type = CODEC_TYPE_AUDIO;
  495. st->codec->codec_id = CODEC_ID_MP2;
  496. } else if (code == 0x1bd) {
  497. st->codec->codec_type = CODEC_TYPE_AUDIO;
  498. st->codec->codec_id = CODEC_ID_AC3;
  499. }
  500. }
  501. return st;
  502. }
  503. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  504. {
  505. MpegTSContext *ts = filter->u.section_filter.opaque;
  506. SectionHeader h1, *h = &h1;
  507. PESContext *pes;
  508. AVStream *st;
  509. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  510. int program_info_length, pcr_pid, pid, stream_type;
  511. int desc_list_len, desc_len, desc_tag;
  512. int comp_page, anc_page;
  513. char language[4];
  514. uint32_t prog_reg_desc = 0; /* registration descriptor */
  515. #ifdef DEBUG
  516. dprintf(ts->stream, "PMT: len %i\n", section_len);
  517. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  518. #endif
  519. p_end = section + section_len - 4;
  520. p = section;
  521. if (parse_section_header(h, &p, p_end) < 0)
  522. return;
  523. dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  524. h->id, h->sec_num, h->last_sec_num);
  525. if (h->tid != PMT_TID)
  526. return;
  527. clear_program(ts, h->id);
  528. pcr_pid = get16(&p, p_end) & 0x1fff;
  529. if (pcr_pid < 0)
  530. return;
  531. add_pid_to_pmt(ts, h->id, pcr_pid);
  532. dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  533. program_info_length = get16(&p, p_end) & 0xfff;
  534. if (program_info_length < 0)
  535. return;
  536. while(program_info_length >= 2) {
  537. uint8_t tag, len;
  538. tag = get8(&p, p_end);
  539. len = get8(&p, p_end);
  540. if(len > program_info_length - 2)
  541. //something else is broken, exit the program_descriptors_loop
  542. break;
  543. program_info_length -= len + 2;
  544. if(tag == 0x05 && len >= 4) { // registration descriptor
  545. prog_reg_desc = bytestream_get_le32(&p);
  546. len -= 4;
  547. }
  548. p += len;
  549. }
  550. p += program_info_length;
  551. if (p >= p_end)
  552. return;
  553. // stop parsing after pmt, we found header
  554. if (!ts->stream->nb_streams)
  555. ts->stop_parse = 1;
  556. for(;;) {
  557. st = 0;
  558. stream_type = get8(&p, p_end);
  559. if (stream_type < 0)
  560. break;
  561. pid = get16(&p, p_end) & 0x1fff;
  562. if (pid < 0)
  563. break;
  564. /* now create ffmpeg stream */
  565. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  566. pes = ts->pids[pid]->u.pes_filter.opaque;
  567. st = pes->st;
  568. } else {
  569. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  570. pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
  571. if (pes)
  572. st = new_pes_av_stream(pes, prog_reg_desc, 0);
  573. }
  574. if (!st)
  575. return;
  576. add_pid_to_pmt(ts, h->id, pid);
  577. av_program_add_stream_index(ts->stream, h->id, st->index);
  578. desc_list_len = get16(&p, p_end) & 0xfff;
  579. if (desc_list_len < 0)
  580. break;
  581. desc_list_end = p + desc_list_len;
  582. if (desc_list_end > p_end)
  583. break;
  584. for(;;) {
  585. desc_tag = get8(&p, desc_list_end);
  586. if (desc_tag < 0)
  587. break;
  588. desc_len = get8(&p, desc_list_end);
  589. if (desc_len < 0)
  590. break;
  591. desc_end = p + desc_len;
  592. if (desc_end > desc_list_end)
  593. break;
  594. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  595. desc_tag, desc_len);
  596. if (st->codec->codec_id == CODEC_ID_NONE &&
  597. stream_type == STREAM_TYPE_PRIVATE_DATA)
  598. mpegts_find_stream_type(st, desc_tag, DESC_types);
  599. switch(desc_tag) {
  600. case 0x59: /* subtitling descriptor */
  601. language[0] = get8(&p, desc_end);
  602. language[1] = get8(&p, desc_end);
  603. language[2] = get8(&p, desc_end);
  604. language[3] = 0;
  605. get8(&p, desc_end);
  606. comp_page = get16(&p, desc_end);
  607. anc_page = get16(&p, desc_end);
  608. st->codec->sub_id = (anc_page << 16) | comp_page;
  609. av_metadata_set(&st->metadata, "language", language);
  610. break;
  611. case 0x0a: /* ISO 639 language descriptor */
  612. language[0] = get8(&p, desc_end);
  613. language[1] = get8(&p, desc_end);
  614. language[2] = get8(&p, desc_end);
  615. language[3] = 0;
  616. av_metadata_set(&st->metadata, "language", language);
  617. break;
  618. case 0x05: /* registration descriptor */
  619. st->codec->codec_tag = bytestream_get_le32(&p);
  620. dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  621. if (st->codec->codec_id == CODEC_ID_NONE &&
  622. stream_type == STREAM_TYPE_PRIVATE_DATA)
  623. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  624. break;
  625. default:
  626. break;
  627. }
  628. p = desc_end;
  629. }
  630. p = desc_list_end;
  631. }
  632. /* all parameters are there */
  633. mpegts_close_filter(ts, filter);
  634. }
  635. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  636. {
  637. MpegTSContext *ts = filter->u.section_filter.opaque;
  638. SectionHeader h1, *h = &h1;
  639. const uint8_t *p, *p_end;
  640. int sid, pmt_pid;
  641. #ifdef DEBUG
  642. dprintf(ts->stream, "PAT:\n");
  643. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  644. #endif
  645. p_end = section + section_len - 4;
  646. p = section;
  647. if (parse_section_header(h, &p, p_end) < 0)
  648. return;
  649. if (h->tid != PAT_TID)
  650. return;
  651. clear_programs(ts);
  652. for(;;) {
  653. sid = get16(&p, p_end);
  654. if (sid < 0)
  655. break;
  656. pmt_pid = get16(&p, p_end) & 0x1fff;
  657. if (pmt_pid < 0)
  658. break;
  659. dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  660. if (sid == 0x0000) {
  661. /* NIT info */
  662. } else {
  663. av_new_program(ts->stream, sid);
  664. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  665. add_pat_entry(ts, sid);
  666. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  667. add_pid_to_pmt(ts, sid, pmt_pid);
  668. }
  669. }
  670. }
  671. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  672. {
  673. MpegTSContext *ts = filter->u.section_filter.opaque;
  674. SectionHeader h1, *h = &h1;
  675. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  676. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  677. char *name, *provider_name;
  678. #ifdef DEBUG
  679. dprintf(ts->stream, "SDT:\n");
  680. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  681. #endif
  682. p_end = section + section_len - 4;
  683. p = section;
  684. if (parse_section_header(h, &p, p_end) < 0)
  685. return;
  686. if (h->tid != SDT_TID)
  687. return;
  688. onid = get16(&p, p_end);
  689. if (onid < 0)
  690. return;
  691. val = get8(&p, p_end);
  692. if (val < 0)
  693. return;
  694. for(;;) {
  695. sid = get16(&p, p_end);
  696. if (sid < 0)
  697. break;
  698. val = get8(&p, p_end);
  699. if (val < 0)
  700. break;
  701. desc_list_len = get16(&p, p_end) & 0xfff;
  702. if (desc_list_len < 0)
  703. break;
  704. desc_list_end = p + desc_list_len;
  705. if (desc_list_end > p_end)
  706. break;
  707. for(;;) {
  708. desc_tag = get8(&p, desc_list_end);
  709. if (desc_tag < 0)
  710. break;
  711. desc_len = get8(&p, desc_list_end);
  712. desc_end = p + desc_len;
  713. if (desc_end > desc_list_end)
  714. break;
  715. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  716. desc_tag, desc_len);
  717. switch(desc_tag) {
  718. case 0x48:
  719. service_type = get8(&p, p_end);
  720. if (service_type < 0)
  721. break;
  722. provider_name = getstr8(&p, p_end);
  723. if (!provider_name)
  724. break;
  725. name = getstr8(&p, p_end);
  726. if (name) {
  727. AVProgram *program = av_new_program(ts->stream, sid);
  728. if(program) {
  729. av_metadata_set(&program->metadata, "name", name);
  730. av_metadata_set(&program->metadata, "provider_name", provider_name);
  731. }
  732. }
  733. av_free(name);
  734. av_free(provider_name);
  735. break;
  736. default:
  737. break;
  738. }
  739. p = desc_end;
  740. }
  741. p = desc_list_end;
  742. }
  743. }
  744. static int64_t get_pts(const uint8_t *p)
  745. {
  746. int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
  747. pts |= (AV_RB16(p + 1) >> 1) << 15;
  748. pts |= AV_RB16(p + 3) >> 1;
  749. return pts;
  750. }
  751. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  752. {
  753. av_init_packet(pkt);
  754. pkt->destruct = av_destruct_packet;
  755. pkt->data = pes->buffer;
  756. pkt->size = pes->data_index;
  757. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  758. pkt->stream_index = pes->st->index;
  759. pkt->pts = pes->pts;
  760. pkt->dts = pes->dts;
  761. /* store position of first TS packet of this PES packet */
  762. pkt->pos = pes->ts_packet_pos;
  763. /* reset pts values */
  764. pes->pts = AV_NOPTS_VALUE;
  765. pes->dts = AV_NOPTS_VALUE;
  766. pes->buffer = NULL;
  767. pes->data_index = 0;
  768. }
  769. /* return non zero if a packet could be constructed */
  770. static int mpegts_push_data(MpegTSFilter *filter,
  771. const uint8_t *buf, int buf_size, int is_start,
  772. int64_t pos)
  773. {
  774. PESContext *pes = filter->u.pes_filter.opaque;
  775. MpegTSContext *ts = pes->ts;
  776. const uint8_t *p;
  777. int len, code;
  778. if(!ts->pkt)
  779. return 0;
  780. if (is_start) {
  781. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  782. new_pes_packet(pes, ts->pkt);
  783. ts->stop_parse = 1;
  784. }
  785. pes->state = MPEGTS_HEADER;
  786. pes->data_index = 0;
  787. pes->ts_packet_pos = pos;
  788. }
  789. p = buf;
  790. while (buf_size > 0) {
  791. switch(pes->state) {
  792. case MPEGTS_HEADER:
  793. len = PES_START_SIZE - pes->data_index;
  794. if (len > buf_size)
  795. len = buf_size;
  796. memcpy(pes->header + pes->data_index, p, len);
  797. pes->data_index += len;
  798. p += len;
  799. buf_size -= len;
  800. if (pes->data_index == PES_START_SIZE) {
  801. /* we got all the PES or section header. We can now
  802. decide */
  803. #if 0
  804. av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
  805. #endif
  806. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  807. pes->header[2] == 0x01) {
  808. /* it must be an mpeg2 PES stream */
  809. code = pes->header[3] | 0x100;
  810. dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  811. if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
  812. (pes->st && pes->st->discard == AVDISCARD_ALL) ||
  813. code == 0x1be) /* padding_stream */
  814. goto skip;
  815. /* stream not present in PMT */
  816. if (!pes->st)
  817. pes->st = new_pes_av_stream(pes, 0, code);
  818. if (!pes->st)
  819. return AVERROR(ENOMEM);
  820. pes->total_size = AV_RB16(pes->header + 4);
  821. /* NOTE: a zero total size means the PES size is
  822. unbounded */
  823. if (!pes->total_size)
  824. pes->total_size = MAX_PES_PAYLOAD;
  825. /* allocate pes buffer */
  826. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  827. if (!pes->buffer)
  828. return AVERROR(ENOMEM);
  829. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  830. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  831. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  832. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  833. pes->state = MPEGTS_PESHEADER;
  834. if (pes->st->codec->codec_id == CODEC_ID_NONE) {
  835. dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
  836. pes->pid, pes->stream_type);
  837. pes->st->codec->codec_id = CODEC_ID_PROBE;
  838. }
  839. } else {
  840. pes->state = MPEGTS_PAYLOAD;
  841. pes->data_index = 0;
  842. }
  843. } else {
  844. /* otherwise, it should be a table */
  845. /* skip packet */
  846. skip:
  847. pes->state = MPEGTS_SKIP;
  848. continue;
  849. }
  850. }
  851. break;
  852. /**********************************************/
  853. /* PES packing parsing */
  854. case MPEGTS_PESHEADER:
  855. len = PES_HEADER_SIZE - pes->data_index;
  856. if (len < 0)
  857. return -1;
  858. if (len > buf_size)
  859. len = buf_size;
  860. memcpy(pes->header + pes->data_index, p, len);
  861. pes->data_index += len;
  862. p += len;
  863. buf_size -= len;
  864. if (pes->data_index == PES_HEADER_SIZE) {
  865. pes->pes_header_size = pes->header[8] + 9;
  866. pes->state = MPEGTS_PESHEADER_FILL;
  867. }
  868. break;
  869. case MPEGTS_PESHEADER_FILL:
  870. len = pes->pes_header_size - pes->data_index;
  871. if (len < 0)
  872. return -1;
  873. if (len > buf_size)
  874. len = buf_size;
  875. memcpy(pes->header + pes->data_index, p, len);
  876. pes->data_index += len;
  877. p += len;
  878. buf_size -= len;
  879. if (pes->data_index == pes->pes_header_size) {
  880. const uint8_t *r;
  881. unsigned int flags;
  882. flags = pes->header[7];
  883. r = pes->header + 9;
  884. pes->pts = AV_NOPTS_VALUE;
  885. pes->dts = AV_NOPTS_VALUE;
  886. if ((flags & 0xc0) == 0x80) {
  887. pes->dts = pes->pts = get_pts(r);
  888. r += 5;
  889. } else if ((flags & 0xc0) == 0xc0) {
  890. pes->pts = get_pts(r);
  891. r += 5;
  892. pes->dts = get_pts(r);
  893. r += 5;
  894. }
  895. /* we got the full header. We parse it and get the payload */
  896. pes->state = MPEGTS_PAYLOAD;
  897. pes->data_index = 0;
  898. }
  899. break;
  900. case MPEGTS_PAYLOAD:
  901. if (buf_size > 0) {
  902. if (pes->data_index+buf_size > pes->total_size) {
  903. new_pes_packet(pes, ts->pkt);
  904. pes->total_size = MAX_PES_PAYLOAD;
  905. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  906. if (!pes->buffer)
  907. return AVERROR(ENOMEM);
  908. ts->stop_parse = 1;
  909. }
  910. memcpy(pes->buffer+pes->data_index, p, buf_size);
  911. pes->data_index += buf_size;
  912. }
  913. buf_size = 0;
  914. break;
  915. case MPEGTS_SKIP:
  916. buf_size = 0;
  917. break;
  918. }
  919. }
  920. return 0;
  921. }
  922. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
  923. {
  924. MpegTSFilter *tss;
  925. PESContext *pes;
  926. /* if no pid found, then add a pid context */
  927. pes = av_mallocz(sizeof(PESContext));
  928. if (!pes)
  929. return 0;
  930. pes->ts = ts;
  931. pes->stream = ts->stream;
  932. pes->pid = pid;
  933. pes->pcr_pid = pcr_pid;
  934. pes->stream_type = stream_type;
  935. pes->state = MPEGTS_SKIP;
  936. pes->pts = AV_NOPTS_VALUE;
  937. pes->dts = AV_NOPTS_VALUE;
  938. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  939. if (!tss) {
  940. av_free(pes);
  941. return 0;
  942. }
  943. return pes;
  944. }
  945. /* handle one TS packet */
  946. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  947. {
  948. AVFormatContext *s = ts->stream;
  949. MpegTSFilter *tss;
  950. int len, pid, cc, cc_ok, afc, is_start;
  951. const uint8_t *p, *p_end;
  952. int64_t pos;
  953. pid = AV_RB16(packet + 1) & 0x1fff;
  954. if(pid && discard_pid(ts, pid))
  955. return 0;
  956. is_start = packet[1] & 0x40;
  957. tss = ts->pids[pid];
  958. if (ts->auto_guess && tss == NULL && is_start) {
  959. add_pes_stream(ts, pid, -1, 0);
  960. tss = ts->pids[pid];
  961. }
  962. if (!tss)
  963. return 0;
  964. /* continuity check (currently not used) */
  965. cc = (packet[3] & 0xf);
  966. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  967. tss->last_cc = cc;
  968. /* skip adaptation field */
  969. afc = (packet[3] >> 4) & 3;
  970. p = packet + 4;
  971. if (afc == 0) /* reserved value */
  972. return 0;
  973. if (afc == 2) /* adaptation field only */
  974. return 0;
  975. if (afc == 3) {
  976. /* skip adapation field */
  977. p += p[0] + 1;
  978. }
  979. /* if past the end of packet, ignore */
  980. p_end = packet + TS_PACKET_SIZE;
  981. if (p >= p_end)
  982. return 0;
  983. pos = url_ftell(ts->stream->pb);
  984. ts->pos47= pos % ts->raw_packet_size;
  985. if (tss->type == MPEGTS_SECTION) {
  986. if (is_start) {
  987. /* pointer field present */
  988. len = *p++;
  989. if (p + len > p_end)
  990. return 0;
  991. if (len && cc_ok) {
  992. /* write remaining section bytes */
  993. write_section_data(s, tss,
  994. p, len, 0);
  995. /* check whether filter has been closed */
  996. if (!ts->pids[pid])
  997. return 0;
  998. }
  999. p += len;
  1000. if (p < p_end) {
  1001. write_section_data(s, tss,
  1002. p, p_end - p, 1);
  1003. }
  1004. } else {
  1005. if (cc_ok) {
  1006. write_section_data(s, tss,
  1007. p, p_end - p, 0);
  1008. }
  1009. }
  1010. } else {
  1011. int ret;
  1012. // Note: The position here points actually behind the current packet.
  1013. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1014. pos - ts->raw_packet_size)) < 0)
  1015. return ret;
  1016. }
  1017. return 0;
  1018. }
  1019. /* XXX: try to find a better synchro over several packets (use
  1020. get_packet_size() ?) */
  1021. static int mpegts_resync(ByteIOContext *pb)
  1022. {
  1023. int c, i;
  1024. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1025. c = url_fgetc(pb);
  1026. if (c < 0)
  1027. return -1;
  1028. if (c == 0x47) {
  1029. url_fseek(pb, -1, SEEK_CUR);
  1030. return 0;
  1031. }
  1032. }
  1033. /* no sync found */
  1034. return -1;
  1035. }
  1036. /* return -1 if error or EOF. Return 0 if OK. */
  1037. static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
  1038. {
  1039. int skip, len;
  1040. for(;;) {
  1041. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  1042. if (len != TS_PACKET_SIZE)
  1043. return AVERROR(EIO);
  1044. /* check paquet sync byte */
  1045. if (buf[0] != 0x47) {
  1046. /* find a new packet start */
  1047. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1048. if (mpegts_resync(pb) < 0)
  1049. return AVERROR_INVALIDDATA;
  1050. else
  1051. continue;
  1052. } else {
  1053. skip = raw_packet_size - TS_PACKET_SIZE;
  1054. if (skip > 0)
  1055. url_fskip(pb, skip);
  1056. break;
  1057. }
  1058. }
  1059. return 0;
  1060. }
  1061. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1062. {
  1063. AVFormatContext *s = ts->stream;
  1064. ByteIOContext *pb = s->pb;
  1065. uint8_t packet[TS_PACKET_SIZE];
  1066. int packet_num, ret;
  1067. ts->stop_parse = 0;
  1068. packet_num = 0;
  1069. for(;;) {
  1070. if (ts->stop_parse>0)
  1071. break;
  1072. packet_num++;
  1073. if (nb_packets != 0 && packet_num >= nb_packets)
  1074. break;
  1075. ret = read_packet(pb, packet, ts->raw_packet_size);
  1076. if (ret != 0)
  1077. return ret;
  1078. ret = handle_packet(ts, packet);
  1079. if (ret != 0)
  1080. return ret;
  1081. }
  1082. return 0;
  1083. }
  1084. static int mpegts_probe(AVProbeData *p)
  1085. {
  1086. #if 1
  1087. const int size= p->buf_size;
  1088. int score, fec_score, dvhs_score;
  1089. int check_count= size / TS_FEC_PACKET_SIZE;
  1090. #define CHECK_COUNT 10
  1091. if (check_count < CHECK_COUNT)
  1092. return -1;
  1093. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1094. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1095. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1096. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1097. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1098. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1099. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1100. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1101. else return -1;
  1102. #else
  1103. /* only use the extension for safer guess */
  1104. if (match_ext(p->filename, "ts"))
  1105. return AVPROBE_SCORE_MAX;
  1106. else
  1107. return 0;
  1108. #endif
  1109. }
  1110. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1111. (-1) if not available */
  1112. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1113. const uint8_t *packet)
  1114. {
  1115. int afc, len, flags;
  1116. const uint8_t *p;
  1117. unsigned int v;
  1118. afc = (packet[3] >> 4) & 3;
  1119. if (afc <= 1)
  1120. return -1;
  1121. p = packet + 4;
  1122. len = p[0];
  1123. p++;
  1124. if (len == 0)
  1125. return -1;
  1126. flags = *p++;
  1127. len--;
  1128. if (!(flags & 0x10))
  1129. return -1;
  1130. if (len < 6)
  1131. return -1;
  1132. v = AV_RB32(p);
  1133. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1134. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1135. return 0;
  1136. }
  1137. static int mpegts_read_header(AVFormatContext *s,
  1138. AVFormatParameters *ap)
  1139. {
  1140. MpegTSContext *ts = s->priv_data;
  1141. ByteIOContext *pb = s->pb;
  1142. uint8_t buf[5*1024];
  1143. int len;
  1144. int64_t pos;
  1145. if (ap) {
  1146. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1147. if(ap->mpeg2ts_raw){
  1148. av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
  1149. return -1;
  1150. }
  1151. }
  1152. /* read the first 1024 bytes to get packet size */
  1153. pos = url_ftell(pb);
  1154. len = get_buffer(pb, buf, sizeof(buf));
  1155. if (len != sizeof(buf))
  1156. goto fail;
  1157. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1158. if (ts->raw_packet_size <= 0)
  1159. goto fail;
  1160. ts->stream = s;
  1161. ts->auto_guess = 0;
  1162. if (s->iformat == &mpegts_demuxer) {
  1163. /* normal demux */
  1164. /* first do a scaning to get all the services */
  1165. url_fseek(pb, pos, SEEK_SET);
  1166. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1167. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1168. handle_packets(ts, s->probesize);
  1169. /* if could not find service, enable auto_guess */
  1170. ts->auto_guess = 1;
  1171. dprintf(ts->stream, "tuning done\n");
  1172. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1173. } else {
  1174. AVStream *st;
  1175. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1176. int64_t pcrs[2], pcr_h;
  1177. int packet_count[2];
  1178. uint8_t packet[TS_PACKET_SIZE];
  1179. /* only read packets */
  1180. st = av_new_stream(s, 0);
  1181. if (!st)
  1182. goto fail;
  1183. av_set_pts_info(st, 60, 1, 27000000);
  1184. st->codec->codec_type = CODEC_TYPE_DATA;
  1185. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1186. /* we iterate until we find two PCRs to estimate the bitrate */
  1187. pcr_pid = -1;
  1188. nb_pcrs = 0;
  1189. nb_packets = 0;
  1190. for(;;) {
  1191. ret = read_packet(s->pb, packet, ts->raw_packet_size);
  1192. if (ret < 0)
  1193. return -1;
  1194. pid = AV_RB16(packet + 1) & 0x1fff;
  1195. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1196. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1197. pcr_pid = pid;
  1198. packet_count[nb_pcrs] = nb_packets;
  1199. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1200. nb_pcrs++;
  1201. if (nb_pcrs >= 2)
  1202. break;
  1203. }
  1204. nb_packets++;
  1205. }
  1206. /* NOTE1: the bitrate is computed without the FEC */
  1207. /* NOTE2: it is only the bitrate of the start of the stream */
  1208. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1209. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1210. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1211. st->codec->bit_rate = s->bit_rate;
  1212. st->start_time = ts->cur_pcr;
  1213. #if 0
  1214. av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
  1215. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1216. #endif
  1217. }
  1218. url_fseek(pb, pos, SEEK_SET);
  1219. return 0;
  1220. fail:
  1221. return -1;
  1222. }
  1223. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1224. static int mpegts_raw_read_packet(AVFormatContext *s,
  1225. AVPacket *pkt)
  1226. {
  1227. MpegTSContext *ts = s->priv_data;
  1228. int ret, i;
  1229. int64_t pcr_h, next_pcr_h, pos;
  1230. int pcr_l, next_pcr_l;
  1231. uint8_t pcr_buf[12];
  1232. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1233. return AVERROR(ENOMEM);
  1234. pkt->pos= url_ftell(s->pb);
  1235. ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
  1236. if (ret < 0) {
  1237. av_free_packet(pkt);
  1238. return ret;
  1239. }
  1240. if (ts->mpeg2ts_compute_pcr) {
  1241. /* compute exact PCR for each packet */
  1242. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1243. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1244. pos = url_ftell(s->pb);
  1245. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1246. url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1247. get_buffer(s->pb, pcr_buf, 12);
  1248. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1249. /* XXX: not precise enough */
  1250. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1251. (i + 1);
  1252. break;
  1253. }
  1254. }
  1255. url_fseek(s->pb, pos, SEEK_SET);
  1256. /* no next PCR found: we use previous increment */
  1257. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1258. }
  1259. pkt->pts = ts->cur_pcr;
  1260. pkt->duration = ts->pcr_incr;
  1261. ts->cur_pcr += ts->pcr_incr;
  1262. }
  1263. pkt->stream_index = 0;
  1264. return 0;
  1265. }
  1266. static int mpegts_read_packet(AVFormatContext *s,
  1267. AVPacket *pkt)
  1268. {
  1269. MpegTSContext *ts = s->priv_data;
  1270. int ret, i;
  1271. if (url_ftell(s->pb) != ts->last_pos) {
  1272. /* seek detected, flush pes buffer */
  1273. for (i = 0; i < NB_PID_MAX; i++) {
  1274. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1275. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1276. av_freep(&pes->buffer);
  1277. pes->data_index = 0;
  1278. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1279. }
  1280. }
  1281. }
  1282. ts->pkt = pkt;
  1283. ret = handle_packets(ts, 0);
  1284. if (ret < 0) {
  1285. /* flush pes data left */
  1286. for (i = 0; i < NB_PID_MAX; i++) {
  1287. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1288. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1289. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1290. new_pes_packet(pes, pkt);
  1291. ret = 0;
  1292. break;
  1293. }
  1294. }
  1295. }
  1296. }
  1297. ts->last_pos = url_ftell(s->pb);
  1298. return ret;
  1299. }
  1300. static int mpegts_read_close(AVFormatContext *s)
  1301. {
  1302. MpegTSContext *ts = s->priv_data;
  1303. int i;
  1304. clear_programs(ts);
  1305. for(i=0;i<NB_PID_MAX;i++)
  1306. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1307. return 0;
  1308. }
  1309. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1310. int64_t *ppos, int64_t pos_limit)
  1311. {
  1312. MpegTSContext *ts = s->priv_data;
  1313. int64_t pos, timestamp;
  1314. uint8_t buf[TS_PACKET_SIZE];
  1315. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1316. const int find_next= 1;
  1317. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1318. if (find_next) {
  1319. for(;;) {
  1320. url_fseek(s->pb, pos, SEEK_SET);
  1321. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1322. return AV_NOPTS_VALUE;
  1323. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1324. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1325. break;
  1326. }
  1327. pos += ts->raw_packet_size;
  1328. }
  1329. } else {
  1330. for(;;) {
  1331. pos -= ts->raw_packet_size;
  1332. if (pos < 0)
  1333. return AV_NOPTS_VALUE;
  1334. url_fseek(s->pb, pos, SEEK_SET);
  1335. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1336. return AV_NOPTS_VALUE;
  1337. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1338. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1339. break;
  1340. }
  1341. }
  1342. }
  1343. *ppos = pos;
  1344. return timestamp;
  1345. }
  1346. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags);
  1347. static int read_seek2(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t target_ts, int64_t max_ts, int flags)
  1348. {
  1349. int64_t pos;
  1350. int64_t ts_ret, ts_adj;
  1351. int stream_index_gen_search;
  1352. AVStream *st;
  1353. AVParserState *backup;
  1354. backup = ff_store_parser_state(s);
  1355. // detect direction of seeking for search purposes
  1356. flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ? AVSEEK_FLAG_BACKWARD : 0;
  1357. if (flags & AVSEEK_FLAG_BYTE) {
  1358. /* use position directly, we will search starting from it */
  1359. pos = target_ts;
  1360. } else {
  1361. /* search for some position with good timestamp match */
  1362. if(stream_index < 0){
  1363. stream_index_gen_search = av_find_default_stream_index(s);
  1364. if (stream_index_gen_search < 0) {
  1365. ff_restore_parser_state(s, backup);
  1366. return -1;
  1367. }
  1368. st = s->streams[stream_index_gen_search];
  1369. /* timestamp for default must be expressed in AV_TIME_BASE units */
  1370. ts_adj = av_rescale(target_ts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1371. } else {
  1372. ts_adj = target_ts;
  1373. stream_index_gen_search = stream_index;
  1374. }
  1375. pos = av_gen_search(s, stream_index_gen_search, ts_adj,
  1376. 0, INT64_MAX, -1,
  1377. AV_NOPTS_VALUE,
  1378. AV_NOPTS_VALUE,
  1379. flags, &ts_ret, mpegts_get_pcr);
  1380. if (pos < 0) {
  1381. ff_restore_parser_state(s, backup);
  1382. return -1;
  1383. }
  1384. }
  1385. /* search for actual matching keyframe/starting position for all streams */
  1386. if (ff_gen_syncpoint_search(s, stream_index, pos, min_ts, target_ts, max_ts, flags) < 0) {
  1387. ff_restore_parser_state(s, backup);
  1388. return -1;
  1389. }
  1390. ff_free_parser_state(s, backup);
  1391. return 0;
  1392. }
  1393. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
  1394. {
  1395. int ret;
  1396. if (flags & AVSEEK_FLAG_BACKWARD) {
  1397. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
  1398. if (ret < 0) {
  1399. // for compatibility reasons, seek to best-fitting timestamp
  1400. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags & ~AVSEEK_FLAG_BACKWARD);
  1401. }
  1402. } else {
  1403. ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
  1404. if (ret < 0) {
  1405. // for compatibility reasons, seek to best-fitting timestamp
  1406. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1407. }
  1408. }
  1409. return ret;
  1410. }
  1411. /**************************************************************/
  1412. /* parsing functions - called from other demuxers such as RTP */
  1413. MpegTSContext *mpegts_parse_open(AVFormatContext *s)
  1414. {
  1415. MpegTSContext *ts;
  1416. ts = av_mallocz(sizeof(MpegTSContext));
  1417. if (!ts)
  1418. return NULL;
  1419. /* no stream case, currently used by RTP */
  1420. ts->raw_packet_size = TS_PACKET_SIZE;
  1421. ts->stream = s;
  1422. ts->auto_guess = 1;
  1423. return ts;
  1424. }
  1425. /* return the consumed length if a packet was output, or -1 if no
  1426. packet is output */
  1427. int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1428. const uint8_t *buf, int len)
  1429. {
  1430. int len1;
  1431. len1 = len;
  1432. ts->pkt = pkt;
  1433. ts->stop_parse = 0;
  1434. for(;;) {
  1435. if (ts->stop_parse>0)
  1436. break;
  1437. if (len < TS_PACKET_SIZE)
  1438. return -1;
  1439. if (buf[0] != 0x47) {
  1440. buf++;
  1441. len--;
  1442. } else {
  1443. handle_packet(ts, buf);
  1444. buf += TS_PACKET_SIZE;
  1445. len -= TS_PACKET_SIZE;
  1446. }
  1447. }
  1448. return len1 - len;
  1449. }
  1450. void mpegts_parse_close(MpegTSContext *ts)
  1451. {
  1452. int i;
  1453. for(i=0;i<NB_PID_MAX;i++)
  1454. av_free(ts->pids[i]);
  1455. av_free(ts);
  1456. }
  1457. AVInputFormat mpegts_demuxer = {
  1458. "mpegts",
  1459. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1460. sizeof(MpegTSContext),
  1461. mpegts_probe,
  1462. mpegts_read_header,
  1463. mpegts_read_packet,
  1464. mpegts_read_close,
  1465. read_seek,
  1466. mpegts_get_pcr,
  1467. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1468. .read_seek2 = read_seek2,
  1469. };
  1470. AVInputFormat mpegtsraw_demuxer = {
  1471. "mpegtsraw",
  1472. NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1473. sizeof(MpegTSContext),
  1474. NULL,
  1475. mpegts_read_header,
  1476. mpegts_raw_read_packet,
  1477. mpegts_read_close,
  1478. read_seek,
  1479. mpegts_get_pcr,
  1480. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1481. .read_seek2 = read_seek2,
  1482. };