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.

1857 lines
57KB

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