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.

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