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.

1575 lines
46KB

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