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.

1592 lines
46KB

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