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.

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