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.

1574 lines
45KB

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