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.

1966 lines
62KB

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