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.

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