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.

2049 lines
63KB

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