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.

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