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.

1879 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 > 0 && 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. } else if (pes->data_index == 0 && buf_size > pes->total_size) {
  711. // pes packet size is < ts size packet and pes data is padded with 0xff
  712. // not sure if this is legal in ts but see issue #2392
  713. buf_size = pes->total_size;
  714. }
  715. memcpy(pes->buffer+pes->data_index, p, buf_size);
  716. pes->data_index += buf_size;
  717. }
  718. buf_size = 0;
  719. /* emit complete packets with known packet size
  720. * decreases demuxer delay for infrequent packets like subtitles from
  721. * a couple of seconds to milliseconds for properly muxed files.
  722. * total_size is the number of bytes following pes_packet_length
  723. * in the pes header, i.e. not counting the first 6 bytes */
  724. if (pes->total_size < MAX_PES_PAYLOAD &&
  725. pes->pes_header_size + pes->data_index == pes->total_size + 6) {
  726. ts->stop_parse = 1;
  727. new_pes_packet(pes, ts->pkt);
  728. }
  729. break;
  730. case MPEGTS_SKIP:
  731. buf_size = 0;
  732. break;
  733. }
  734. }
  735. return 0;
  736. }
  737. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  738. {
  739. MpegTSFilter *tss;
  740. PESContext *pes;
  741. /* if no pid found, then add a pid context */
  742. pes = av_mallocz(sizeof(PESContext));
  743. if (!pes)
  744. return 0;
  745. pes->ts = ts;
  746. pes->stream = ts->stream;
  747. pes->pid = pid;
  748. pes->pcr_pid = pcr_pid;
  749. pes->state = MPEGTS_SKIP;
  750. pes->pts = AV_NOPTS_VALUE;
  751. pes->dts = AV_NOPTS_VALUE;
  752. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  753. if (!tss) {
  754. av_free(pes);
  755. return 0;
  756. }
  757. return pes;
  758. }
  759. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  760. int *es_id, uint8_t **dec_config_descr,
  761. int *dec_config_descr_size)
  762. {
  763. ByteIOContext pb;
  764. int tag;
  765. unsigned len;
  766. init_put_byte(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
  767. len = ff_mp4_read_descr(s, &pb, &tag);
  768. if (tag == MP4IODescrTag) {
  769. get_be16(&pb); // ID
  770. get_byte(&pb);
  771. get_byte(&pb);
  772. get_byte(&pb);
  773. get_byte(&pb);
  774. get_byte(&pb);
  775. len = ff_mp4_read_descr(s, &pb, &tag);
  776. if (tag == MP4ESDescrTag) {
  777. *es_id = get_be16(&pb); /* ES_ID */
  778. dprintf(s, "ES_ID %#x\n", *es_id);
  779. get_byte(&pb); /* priority */
  780. len = ff_mp4_read_descr(s, &pb, &tag);
  781. if (tag == MP4DecConfigDescrTag) {
  782. *dec_config_descr = av_malloc(len);
  783. if (!*dec_config_descr)
  784. return AVERROR(ENOMEM);
  785. *dec_config_descr_size = len;
  786. get_buffer(&pb, *dec_config_descr, len);
  787. }
  788. }
  789. }
  790. return 0;
  791. }
  792. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  793. const uint8_t **pp, const uint8_t *desc_list_end,
  794. int mp4_dec_config_descr_len, int mp4_es_id, int pid,
  795. uint8_t *mp4_dec_config_descr)
  796. {
  797. const uint8_t *desc_end;
  798. int desc_len, desc_tag;
  799. char language[4];
  800. desc_tag = get8(pp, desc_list_end);
  801. if (desc_tag < 0)
  802. return -1;
  803. desc_len = get8(pp, desc_list_end);
  804. if (desc_len < 0)
  805. return -1;
  806. desc_end = *pp + desc_len;
  807. if (desc_end > desc_list_end)
  808. return -1;
  809. dprintf(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  810. if (st->codec->codec_id == CODEC_ID_NONE &&
  811. stream_type == STREAM_TYPE_PRIVATE_DATA)
  812. mpegts_find_stream_type(st, desc_tag, DESC_types);
  813. switch(desc_tag) {
  814. case 0x1F: /* FMC descriptor */
  815. get16(pp, desc_end);
  816. if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
  817. mp4_dec_config_descr_len && mp4_es_id == pid) {
  818. ByteIOContext pb;
  819. init_put_byte(&pb, mp4_dec_config_descr,
  820. mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  821. ff_mp4_read_dec_config_descr(fc, st, &pb);
  822. if (st->codec->codec_id == CODEC_ID_AAC &&
  823. st->codec->extradata_size > 0)
  824. st->need_parsing = 0;
  825. }
  826. break;
  827. case 0x56: /* DVB teletext descriptor */
  828. language[0] = get8(pp, desc_end);
  829. language[1] = get8(pp, desc_end);
  830. language[2] = get8(pp, desc_end);
  831. language[3] = 0;
  832. av_metadata_set2(&st->metadata, "language", language, 0);
  833. break;
  834. case 0x59: /* subtitling descriptor */
  835. language[0] = get8(pp, desc_end);
  836. language[1] = get8(pp, desc_end);
  837. language[2] = get8(pp, desc_end);
  838. language[3] = 0;
  839. get8(pp, desc_end);
  840. if (st->codec->extradata) {
  841. if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
  842. av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
  843. } else {
  844. st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
  845. if (st->codec->extradata) {
  846. st->codec->extradata_size = 4;
  847. memcpy(st->codec->extradata, *pp, 4);
  848. }
  849. }
  850. *pp += 4;
  851. av_metadata_set2(&st->metadata, "language", language, 0);
  852. break;
  853. case 0x0a: /* ISO 639 language descriptor */
  854. language[0] = get8(pp, desc_end);
  855. language[1] = get8(pp, desc_end);
  856. language[2] = get8(pp, desc_end);
  857. language[3] = 0;
  858. av_metadata_set2(&st->metadata, "language", language, 0);
  859. break;
  860. case 0x05: /* registration descriptor */
  861. st->codec->codec_tag = bytestream_get_le32(pp);
  862. dprintf(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  863. if (st->codec->codec_id == CODEC_ID_NONE &&
  864. stream_type == STREAM_TYPE_PRIVATE_DATA)
  865. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  866. break;
  867. default:
  868. break;
  869. }
  870. *pp = desc_end;
  871. return 0;
  872. }
  873. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  874. {
  875. MpegTSContext *ts = filter->u.section_filter.opaque;
  876. SectionHeader h1, *h = &h1;
  877. PESContext *pes;
  878. AVStream *st;
  879. const uint8_t *p, *p_end, *desc_list_end;
  880. int program_info_length, pcr_pid, pid, stream_type;
  881. int desc_list_len;
  882. uint32_t prog_reg_desc = 0; /* registration descriptor */
  883. uint8_t *mp4_dec_config_descr = NULL;
  884. int mp4_dec_config_descr_len = 0;
  885. int mp4_es_id = 0;
  886. #ifdef DEBUG
  887. dprintf(ts->stream, "PMT: len %i\n", section_len);
  888. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  889. #endif
  890. p_end = section + section_len - 4;
  891. p = section;
  892. if (parse_section_header(h, &p, p_end) < 0)
  893. return;
  894. dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  895. h->id, h->sec_num, h->last_sec_num);
  896. if (h->tid != PMT_TID)
  897. return;
  898. clear_program(ts, h->id);
  899. pcr_pid = get16(&p, p_end) & 0x1fff;
  900. if (pcr_pid < 0)
  901. return;
  902. add_pid_to_pmt(ts, h->id, pcr_pid);
  903. dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  904. program_info_length = get16(&p, p_end) & 0xfff;
  905. if (program_info_length < 0)
  906. return;
  907. while(program_info_length >= 2) {
  908. uint8_t tag, len;
  909. tag = get8(&p, p_end);
  910. len = get8(&p, p_end);
  911. dprintf(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  912. if(len > program_info_length - 2)
  913. //something else is broken, exit the program_descriptors_loop
  914. break;
  915. program_info_length -= len + 2;
  916. if (tag == 0x1d) { // IOD descriptor
  917. get8(&p, p_end); // scope
  918. get8(&p, p_end); // label
  919. len -= 2;
  920. mp4_read_iods(ts->stream, p, len, &mp4_es_id,
  921. &mp4_dec_config_descr, &mp4_dec_config_descr_len);
  922. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  923. prog_reg_desc = bytestream_get_le32(&p);
  924. len -= 4;
  925. }
  926. p += len;
  927. }
  928. p += program_info_length;
  929. if (p >= p_end)
  930. goto out;
  931. // stop parsing after pmt, we found header
  932. if (!ts->stream->nb_streams)
  933. ts->stop_parse = 1;
  934. for(;;) {
  935. st = 0;
  936. stream_type = get8(&p, p_end);
  937. if (stream_type < 0)
  938. break;
  939. pid = get16(&p, p_end) & 0x1fff;
  940. if (pid < 0)
  941. break;
  942. /* now create ffmpeg stream */
  943. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  944. pes = ts->pids[pid]->u.pes_filter.opaque;
  945. if (!pes->st)
  946. pes->st = av_new_stream(pes->stream, pes->pid);
  947. st = pes->st;
  948. } else {
  949. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  950. pes = add_pes_stream(ts, pid, pcr_pid);
  951. if (pes)
  952. st = av_new_stream(pes->stream, pes->pid);
  953. }
  954. if (!st)
  955. goto out;
  956. if (!pes->stream_type)
  957. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  958. add_pid_to_pmt(ts, h->id, pid);
  959. ff_program_add_stream_index(ts->stream, h->id, st->index);
  960. desc_list_len = get16(&p, p_end) & 0xfff;
  961. if (desc_list_len < 0)
  962. break;
  963. desc_list_end = p + desc_list_len;
  964. if (desc_list_end > p_end)
  965. break;
  966. for(;;) {
  967. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
  968. mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
  969. break;
  970. if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  971. ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  972. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  973. }
  974. }
  975. p = desc_list_end;
  976. }
  977. out:
  978. av_free(mp4_dec_config_descr);
  979. }
  980. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  981. {
  982. MpegTSContext *ts = filter->u.section_filter.opaque;
  983. SectionHeader h1, *h = &h1;
  984. const uint8_t *p, *p_end;
  985. int sid, pmt_pid;
  986. #ifdef DEBUG
  987. dprintf(ts->stream, "PAT:\n");
  988. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  989. #endif
  990. p_end = section + section_len - 4;
  991. p = section;
  992. if (parse_section_header(h, &p, p_end) < 0)
  993. return;
  994. if (h->tid != PAT_TID)
  995. return;
  996. clear_programs(ts);
  997. for(;;) {
  998. sid = get16(&p, p_end);
  999. if (sid < 0)
  1000. break;
  1001. pmt_pid = get16(&p, p_end) & 0x1fff;
  1002. if (pmt_pid < 0)
  1003. break;
  1004. dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1005. if (sid == 0x0000) {
  1006. /* NIT info */
  1007. } else {
  1008. av_new_program(ts->stream, sid);
  1009. if (ts->pids[pmt_pid])
  1010. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1011. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1012. add_pat_entry(ts, sid);
  1013. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  1014. add_pid_to_pmt(ts, sid, pmt_pid);
  1015. }
  1016. }
  1017. }
  1018. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1019. {
  1020. MpegTSContext *ts = filter->u.section_filter.opaque;
  1021. SectionHeader h1, *h = &h1;
  1022. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1023. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1024. char *name, *provider_name;
  1025. #ifdef DEBUG
  1026. dprintf(ts->stream, "SDT:\n");
  1027. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  1028. #endif
  1029. p_end = section + section_len - 4;
  1030. p = section;
  1031. if (parse_section_header(h, &p, p_end) < 0)
  1032. return;
  1033. if (h->tid != SDT_TID)
  1034. return;
  1035. onid = get16(&p, p_end);
  1036. if (onid < 0)
  1037. return;
  1038. val = get8(&p, p_end);
  1039. if (val < 0)
  1040. return;
  1041. for(;;) {
  1042. sid = get16(&p, p_end);
  1043. if (sid < 0)
  1044. break;
  1045. val = get8(&p, p_end);
  1046. if (val < 0)
  1047. break;
  1048. desc_list_len = get16(&p, p_end) & 0xfff;
  1049. if (desc_list_len < 0)
  1050. break;
  1051. desc_list_end = p + desc_list_len;
  1052. if (desc_list_end > p_end)
  1053. break;
  1054. for(;;) {
  1055. desc_tag = get8(&p, desc_list_end);
  1056. if (desc_tag < 0)
  1057. break;
  1058. desc_len = get8(&p, desc_list_end);
  1059. desc_end = p + desc_len;
  1060. if (desc_end > desc_list_end)
  1061. break;
  1062. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  1063. desc_tag, desc_len);
  1064. switch(desc_tag) {
  1065. case 0x48:
  1066. service_type = get8(&p, p_end);
  1067. if (service_type < 0)
  1068. break;
  1069. provider_name = getstr8(&p, p_end);
  1070. if (!provider_name)
  1071. break;
  1072. name = getstr8(&p, p_end);
  1073. if (name) {
  1074. AVProgram *program = av_new_program(ts->stream, sid);
  1075. if(program) {
  1076. av_metadata_set2(&program->metadata, "service_name", name, 0);
  1077. av_metadata_set2(&program->metadata, "service_provider", provider_name, 0);
  1078. }
  1079. }
  1080. av_free(name);
  1081. av_free(provider_name);
  1082. break;
  1083. default:
  1084. break;
  1085. }
  1086. p = desc_end;
  1087. }
  1088. p = desc_list_end;
  1089. }
  1090. }
  1091. /* handle one TS packet */
  1092. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1093. {
  1094. AVFormatContext *s = ts->stream;
  1095. MpegTSFilter *tss;
  1096. int len, pid, cc, cc_ok, afc, is_start;
  1097. const uint8_t *p, *p_end;
  1098. int64_t pos;
  1099. pid = AV_RB16(packet + 1) & 0x1fff;
  1100. if(pid && discard_pid(ts, pid))
  1101. return 0;
  1102. is_start = packet[1] & 0x40;
  1103. tss = ts->pids[pid];
  1104. if (ts->auto_guess && tss == NULL && is_start) {
  1105. add_pes_stream(ts, pid, -1);
  1106. tss = ts->pids[pid];
  1107. }
  1108. if (!tss)
  1109. return 0;
  1110. /* continuity check (currently not used) */
  1111. cc = (packet[3] & 0xf);
  1112. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  1113. tss->last_cc = cc;
  1114. /* skip adaptation field */
  1115. afc = (packet[3] >> 4) & 3;
  1116. p = packet + 4;
  1117. if (afc == 0) /* reserved value */
  1118. return 0;
  1119. if (afc == 2) /* adaptation field only */
  1120. return 0;
  1121. if (afc == 3) {
  1122. /* skip adapation field */
  1123. p += p[0] + 1;
  1124. }
  1125. /* if past the end of packet, ignore */
  1126. p_end = packet + TS_PACKET_SIZE;
  1127. if (p >= p_end)
  1128. return 0;
  1129. pos = url_ftell(ts->stream->pb);
  1130. ts->pos47= pos % ts->raw_packet_size;
  1131. if (tss->type == MPEGTS_SECTION) {
  1132. if (is_start) {
  1133. /* pointer field present */
  1134. len = *p++;
  1135. if (p + len > p_end)
  1136. return 0;
  1137. if (len && cc_ok) {
  1138. /* write remaining section bytes */
  1139. write_section_data(s, tss,
  1140. p, len, 0);
  1141. /* check whether filter has been closed */
  1142. if (!ts->pids[pid])
  1143. return 0;
  1144. }
  1145. p += len;
  1146. if (p < p_end) {
  1147. write_section_data(s, tss,
  1148. p, p_end - p, 1);
  1149. }
  1150. } else {
  1151. if (cc_ok) {
  1152. write_section_data(s, tss,
  1153. p, p_end - p, 0);
  1154. }
  1155. }
  1156. } else {
  1157. int ret;
  1158. // Note: The position here points actually behind the current packet.
  1159. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1160. pos - ts->raw_packet_size)) < 0)
  1161. return ret;
  1162. }
  1163. return 0;
  1164. }
  1165. /* XXX: try to find a better synchro over several packets (use
  1166. get_packet_size() ?) */
  1167. static int mpegts_resync(AVFormatContext *s)
  1168. {
  1169. ByteIOContext *pb = s->pb;
  1170. int c, i;
  1171. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1172. c = url_fgetc(pb);
  1173. if (c < 0)
  1174. return -1;
  1175. if (c == 0x47) {
  1176. url_fseek(pb, -1, SEEK_CUR);
  1177. return 0;
  1178. }
  1179. }
  1180. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1181. /* no sync found */
  1182. return -1;
  1183. }
  1184. /* return -1 if error or EOF. Return 0 if OK. */
  1185. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1186. {
  1187. ByteIOContext *pb = s->pb;
  1188. int skip, len;
  1189. for(;;) {
  1190. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  1191. if (len != TS_PACKET_SIZE)
  1192. return AVERROR(EIO);
  1193. /* check paquet sync byte */
  1194. if (buf[0] != 0x47) {
  1195. /* find a new packet start */
  1196. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1197. if (mpegts_resync(s) < 0)
  1198. return AVERROR(EAGAIN);
  1199. else
  1200. continue;
  1201. } else {
  1202. skip = raw_packet_size - TS_PACKET_SIZE;
  1203. if (skip > 0)
  1204. url_fskip(pb, skip);
  1205. break;
  1206. }
  1207. }
  1208. return 0;
  1209. }
  1210. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1211. {
  1212. AVFormatContext *s = ts->stream;
  1213. uint8_t packet[TS_PACKET_SIZE];
  1214. int packet_num, ret;
  1215. ts->stop_parse = 0;
  1216. packet_num = 0;
  1217. for(;;) {
  1218. if (ts->stop_parse>0)
  1219. break;
  1220. packet_num++;
  1221. if (nb_packets != 0 && packet_num >= nb_packets)
  1222. break;
  1223. ret = read_packet(s, packet, ts->raw_packet_size);
  1224. if (ret != 0)
  1225. return ret;
  1226. ret = handle_packet(ts, packet);
  1227. if (ret != 0)
  1228. return ret;
  1229. }
  1230. return 0;
  1231. }
  1232. static int mpegts_probe(AVProbeData *p)
  1233. {
  1234. #if 1
  1235. const int size= p->buf_size;
  1236. int score, fec_score, dvhs_score;
  1237. int check_count= size / TS_FEC_PACKET_SIZE;
  1238. #define CHECK_COUNT 10
  1239. if (check_count < CHECK_COUNT)
  1240. return -1;
  1241. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1242. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1243. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1244. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1245. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1246. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1247. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1248. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1249. else return -1;
  1250. #else
  1251. /* only use the extension for safer guess */
  1252. if (av_match_ext(p->filename, "ts"))
  1253. return AVPROBE_SCORE_MAX;
  1254. else
  1255. return 0;
  1256. #endif
  1257. }
  1258. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1259. (-1) if not available */
  1260. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1261. const uint8_t *packet)
  1262. {
  1263. int afc, len, flags;
  1264. const uint8_t *p;
  1265. unsigned int v;
  1266. afc = (packet[3] >> 4) & 3;
  1267. if (afc <= 1)
  1268. return -1;
  1269. p = packet + 4;
  1270. len = p[0];
  1271. p++;
  1272. if (len == 0)
  1273. return -1;
  1274. flags = *p++;
  1275. len--;
  1276. if (!(flags & 0x10))
  1277. return -1;
  1278. if (len < 6)
  1279. return -1;
  1280. v = AV_RB32(p);
  1281. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1282. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1283. return 0;
  1284. }
  1285. static int mpegts_read_header(AVFormatContext *s,
  1286. AVFormatParameters *ap)
  1287. {
  1288. MpegTSContext *ts = s->priv_data;
  1289. ByteIOContext *pb = s->pb;
  1290. uint8_t buf[5*1024];
  1291. int len;
  1292. int64_t pos;
  1293. if (ap) {
  1294. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1295. if(ap->mpeg2ts_raw){
  1296. av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
  1297. return -1;
  1298. }
  1299. }
  1300. /* read the first 1024 bytes to get packet size */
  1301. pos = url_ftell(pb);
  1302. len = get_buffer(pb, buf, sizeof(buf));
  1303. if (len != sizeof(buf))
  1304. goto fail;
  1305. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1306. if (ts->raw_packet_size <= 0)
  1307. goto fail;
  1308. ts->stream = s;
  1309. ts->auto_guess = 0;
  1310. if (s->iformat == &mpegts_demuxer) {
  1311. /* normal demux */
  1312. /* first do a scaning to get all the services */
  1313. if (url_fseek(pb, pos, SEEK_SET) < 0)
  1314. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1315. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1316. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1317. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1318. /* if could not find service, enable auto_guess */
  1319. ts->auto_guess = 1;
  1320. dprintf(ts->stream, "tuning done\n");
  1321. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1322. } else {
  1323. AVStream *st;
  1324. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1325. int64_t pcrs[2], pcr_h;
  1326. int packet_count[2];
  1327. uint8_t packet[TS_PACKET_SIZE];
  1328. /* only read packets */
  1329. st = av_new_stream(s, 0);
  1330. if (!st)
  1331. goto fail;
  1332. av_set_pts_info(st, 60, 1, 27000000);
  1333. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1334. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1335. /* we iterate until we find two PCRs to estimate the bitrate */
  1336. pcr_pid = -1;
  1337. nb_pcrs = 0;
  1338. nb_packets = 0;
  1339. for(;;) {
  1340. ret = read_packet(s, packet, ts->raw_packet_size);
  1341. if (ret < 0)
  1342. return -1;
  1343. pid = AV_RB16(packet + 1) & 0x1fff;
  1344. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1345. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1346. pcr_pid = pid;
  1347. packet_count[nb_pcrs] = nb_packets;
  1348. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1349. nb_pcrs++;
  1350. if (nb_pcrs >= 2)
  1351. break;
  1352. }
  1353. nb_packets++;
  1354. }
  1355. /* NOTE1: the bitrate is computed without the FEC */
  1356. /* NOTE2: it is only the bitrate of the start of the stream */
  1357. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1358. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1359. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1360. st->codec->bit_rate = s->bit_rate;
  1361. st->start_time = ts->cur_pcr;
  1362. #if 0
  1363. av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
  1364. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1365. #endif
  1366. }
  1367. url_fseek(pb, pos, SEEK_SET);
  1368. return 0;
  1369. fail:
  1370. return -1;
  1371. }
  1372. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1373. static int mpegts_raw_read_packet(AVFormatContext *s,
  1374. AVPacket *pkt)
  1375. {
  1376. MpegTSContext *ts = s->priv_data;
  1377. int ret, i;
  1378. int64_t pcr_h, next_pcr_h, pos;
  1379. int pcr_l, next_pcr_l;
  1380. uint8_t pcr_buf[12];
  1381. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1382. return AVERROR(ENOMEM);
  1383. pkt->pos= url_ftell(s->pb);
  1384. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1385. if (ret < 0) {
  1386. av_free_packet(pkt);
  1387. return ret;
  1388. }
  1389. if (ts->mpeg2ts_compute_pcr) {
  1390. /* compute exact PCR for each packet */
  1391. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1392. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1393. pos = url_ftell(s->pb);
  1394. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1395. url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1396. get_buffer(s->pb, pcr_buf, 12);
  1397. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1398. /* XXX: not precise enough */
  1399. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1400. (i + 1);
  1401. break;
  1402. }
  1403. }
  1404. url_fseek(s->pb, pos, SEEK_SET);
  1405. /* no next PCR found: we use previous increment */
  1406. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1407. }
  1408. pkt->pts = ts->cur_pcr;
  1409. pkt->duration = ts->pcr_incr;
  1410. ts->cur_pcr += ts->pcr_incr;
  1411. }
  1412. pkt->stream_index = 0;
  1413. return 0;
  1414. }
  1415. static int mpegts_read_packet(AVFormatContext *s,
  1416. AVPacket *pkt)
  1417. {
  1418. MpegTSContext *ts = s->priv_data;
  1419. int ret, i;
  1420. if (url_ftell(s->pb) != ts->last_pos) {
  1421. /* seek detected, flush pes buffer */
  1422. for (i = 0; i < NB_PID_MAX; i++) {
  1423. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1424. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1425. av_freep(&pes->buffer);
  1426. pes->data_index = 0;
  1427. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1428. }
  1429. }
  1430. }
  1431. ts->pkt = pkt;
  1432. ret = handle_packets(ts, 0);
  1433. if (ret < 0) {
  1434. /* flush pes data left */
  1435. for (i = 0; i < NB_PID_MAX; i++) {
  1436. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1437. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1438. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1439. new_pes_packet(pes, pkt);
  1440. pes->state = MPEGTS_SKIP;
  1441. ret = 0;
  1442. break;
  1443. }
  1444. }
  1445. }
  1446. }
  1447. ts->last_pos = url_ftell(s->pb);
  1448. return ret;
  1449. }
  1450. static int mpegts_read_close(AVFormatContext *s)
  1451. {
  1452. MpegTSContext *ts = s->priv_data;
  1453. int i;
  1454. clear_programs(ts);
  1455. for(i=0;i<NB_PID_MAX;i++)
  1456. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1457. return 0;
  1458. }
  1459. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1460. int64_t *ppos, int64_t pos_limit)
  1461. {
  1462. MpegTSContext *ts = s->priv_data;
  1463. int64_t pos, timestamp;
  1464. uint8_t buf[TS_PACKET_SIZE];
  1465. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1466. const int find_next= 1;
  1467. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1468. if (find_next) {
  1469. for(;;) {
  1470. url_fseek(s->pb, pos, SEEK_SET);
  1471. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1472. return AV_NOPTS_VALUE;
  1473. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1474. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1475. break;
  1476. }
  1477. pos += ts->raw_packet_size;
  1478. }
  1479. } else {
  1480. for(;;) {
  1481. pos -= ts->raw_packet_size;
  1482. if (pos < 0)
  1483. return AV_NOPTS_VALUE;
  1484. url_fseek(s->pb, pos, SEEK_SET);
  1485. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1486. return AV_NOPTS_VALUE;
  1487. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1488. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1489. break;
  1490. }
  1491. }
  1492. }
  1493. *ppos = pos;
  1494. return timestamp;
  1495. }
  1496. #ifdef USE_SYNCPOINT_SEARCH
  1497. static int read_seek2(AVFormatContext *s,
  1498. int stream_index,
  1499. int64_t min_ts,
  1500. int64_t target_ts,
  1501. int64_t max_ts,
  1502. int flags)
  1503. {
  1504. int64_t pos;
  1505. int64_t ts_ret, ts_adj;
  1506. int stream_index_gen_search;
  1507. AVStream *st;
  1508. AVParserState *backup;
  1509. backup = ff_store_parser_state(s);
  1510. // detect direction of seeking for search purposes
  1511. flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
  1512. AVSEEK_FLAG_BACKWARD : 0;
  1513. if (flags & AVSEEK_FLAG_BYTE) {
  1514. // use position directly, we will search starting from it
  1515. pos = target_ts;
  1516. } else {
  1517. // search for some position with good timestamp match
  1518. if (stream_index < 0) {
  1519. stream_index_gen_search = av_find_default_stream_index(s);
  1520. if (stream_index_gen_search < 0) {
  1521. ff_restore_parser_state(s, backup);
  1522. return -1;
  1523. }
  1524. st = s->streams[stream_index_gen_search];
  1525. // timestamp for default must be expressed in AV_TIME_BASE units
  1526. ts_adj = av_rescale(target_ts,
  1527. st->time_base.den,
  1528. AV_TIME_BASE * (int64_t)st->time_base.num);
  1529. } else {
  1530. ts_adj = target_ts;
  1531. stream_index_gen_search = stream_index;
  1532. }
  1533. pos = av_gen_search(s, stream_index_gen_search, ts_adj,
  1534. 0, INT64_MAX, -1,
  1535. AV_NOPTS_VALUE,
  1536. AV_NOPTS_VALUE,
  1537. flags, &ts_ret, mpegts_get_pcr);
  1538. if (pos < 0) {
  1539. ff_restore_parser_state(s, backup);
  1540. return -1;
  1541. }
  1542. }
  1543. // search for actual matching keyframe/starting position for all streams
  1544. if (ff_gen_syncpoint_search(s, stream_index, pos,
  1545. min_ts, target_ts, max_ts,
  1546. flags) < 0) {
  1547. ff_restore_parser_state(s, backup);
  1548. return -1;
  1549. }
  1550. ff_free_parser_state(s, backup);
  1551. return 0;
  1552. }
  1553. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
  1554. {
  1555. int ret;
  1556. if (flags & AVSEEK_FLAG_BACKWARD) {
  1557. flags &= ~AVSEEK_FLAG_BACKWARD;
  1558. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
  1559. if (ret < 0)
  1560. // for compatibility reasons, seek to the best-fitting timestamp
  1561. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1562. } else {
  1563. ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
  1564. if (ret < 0)
  1565. // for compatibility reasons, seek to the best-fitting timestamp
  1566. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1567. }
  1568. return ret;
  1569. }
  1570. #else
  1571. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1572. MpegTSContext *ts = s->priv_data;
  1573. uint8_t buf[TS_PACKET_SIZE];
  1574. int64_t pos;
  1575. if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1576. return -1;
  1577. pos= url_ftell(s->pb);
  1578. for(;;) {
  1579. url_fseek(s->pb, pos, SEEK_SET);
  1580. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1581. return -1;
  1582. // pid = AV_RB16(buf + 1) & 0x1fff;
  1583. if(buf[1] & 0x40) break;
  1584. pos += ts->raw_packet_size;
  1585. }
  1586. url_fseek(s->pb, pos, SEEK_SET);
  1587. return 0;
  1588. }
  1589. #endif
  1590. /**************************************************************/
  1591. /* parsing functions - called from other demuxers such as RTP */
  1592. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1593. {
  1594. MpegTSContext *ts;
  1595. ts = av_mallocz(sizeof(MpegTSContext));
  1596. if (!ts)
  1597. return NULL;
  1598. /* no stream case, currently used by RTP */
  1599. ts->raw_packet_size = TS_PACKET_SIZE;
  1600. ts->stream = s;
  1601. ts->auto_guess = 1;
  1602. return ts;
  1603. }
  1604. /* return the consumed length if a packet was output, or -1 if no
  1605. packet is output */
  1606. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1607. const uint8_t *buf, int len)
  1608. {
  1609. int len1;
  1610. len1 = len;
  1611. ts->pkt = pkt;
  1612. ts->stop_parse = 0;
  1613. for(;;) {
  1614. if (ts->stop_parse>0)
  1615. break;
  1616. if (len < TS_PACKET_SIZE)
  1617. return -1;
  1618. if (buf[0] != 0x47) {
  1619. buf++;
  1620. len--;
  1621. } else {
  1622. handle_packet(ts, buf);
  1623. buf += TS_PACKET_SIZE;
  1624. len -= TS_PACKET_SIZE;
  1625. }
  1626. }
  1627. return len1 - len;
  1628. }
  1629. void ff_mpegts_parse_close(MpegTSContext *ts)
  1630. {
  1631. int i;
  1632. for(i=0;i<NB_PID_MAX;i++)
  1633. av_free(ts->pids[i]);
  1634. av_free(ts);
  1635. }
  1636. AVInputFormat mpegts_demuxer = {
  1637. "mpegts",
  1638. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1639. sizeof(MpegTSContext),
  1640. mpegts_probe,
  1641. mpegts_read_header,
  1642. mpegts_read_packet,
  1643. mpegts_read_close,
  1644. read_seek,
  1645. mpegts_get_pcr,
  1646. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1647. #ifdef USE_SYNCPOINT_SEARCH
  1648. .read_seek2 = read_seek2,
  1649. #endif
  1650. };
  1651. AVInputFormat mpegtsraw_demuxer = {
  1652. "mpegtsraw",
  1653. NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1654. sizeof(MpegTSContext),
  1655. NULL,
  1656. mpegts_read_header,
  1657. mpegts_raw_read_packet,
  1658. mpegts_read_close,
  1659. read_seek,
  1660. mpegts_get_pcr,
  1661. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1662. #ifdef USE_SYNCPOINT_SEARCH
  1663. .read_seek2 = read_seek2,
  1664. #endif
  1665. };