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.

2284 lines
71KB

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