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.

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