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.

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