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.

1785 lines
53KB

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