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.

1961 lines
61KB

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