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.

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