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.

2188 lines
69KB

  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. #include "libavutil/buffer.h"
  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. {.i64 = 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. AVBufferRef *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_buffer_unref(&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_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  358. score, dvhs_score, fec_score);
  359. if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  360. else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  361. else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  362. else return -1;
  363. }
  364. typedef struct SectionHeader {
  365. uint8_t tid;
  366. uint16_t id;
  367. uint8_t version;
  368. uint8_t sec_num;
  369. uint8_t last_sec_num;
  370. } SectionHeader;
  371. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  372. {
  373. const uint8_t *p;
  374. int c;
  375. p = *pp;
  376. if (p >= p_end)
  377. return -1;
  378. c = *p++;
  379. *pp = p;
  380. return c;
  381. }
  382. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  383. {
  384. const uint8_t *p;
  385. int c;
  386. p = *pp;
  387. if ((p + 1) >= p_end)
  388. return -1;
  389. c = AV_RB16(p);
  390. p += 2;
  391. *pp = p;
  392. return c;
  393. }
  394. /* read and allocate a DVB string preceded by its length */
  395. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  396. {
  397. int len;
  398. const uint8_t *p;
  399. char *str;
  400. p = *pp;
  401. len = get8(&p, p_end);
  402. if (len < 0)
  403. return NULL;
  404. if ((p + len) > p_end)
  405. return NULL;
  406. str = av_malloc(len + 1);
  407. if (!str)
  408. return NULL;
  409. memcpy(str, p, len);
  410. str[len] = '\0';
  411. p += len;
  412. *pp = p;
  413. return str;
  414. }
  415. static int parse_section_header(SectionHeader *h,
  416. const uint8_t **pp, const uint8_t *p_end)
  417. {
  418. int val;
  419. val = get8(pp, p_end);
  420. if (val < 0)
  421. return -1;
  422. h->tid = val;
  423. *pp += 2;
  424. val = get16(pp, p_end);
  425. if (val < 0)
  426. return -1;
  427. h->id = val;
  428. val = get8(pp, p_end);
  429. if (val < 0)
  430. return -1;
  431. h->version = (val >> 1) & 0x1f;
  432. val = get8(pp, p_end);
  433. if (val < 0)
  434. return -1;
  435. h->sec_num = val;
  436. val = get8(pp, p_end);
  437. if (val < 0)
  438. return -1;
  439. h->last_sec_num = val;
  440. return 0;
  441. }
  442. typedef struct {
  443. uint32_t stream_type;
  444. enum AVMediaType codec_type;
  445. enum AVCodecID codec_id;
  446. } StreamType;
  447. static const StreamType ISO_types[] = {
  448. { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  449. { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  450. { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  451. { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  452. { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
  453. { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
  454. { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
  455. { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
  456. { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  457. { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  458. { 0 },
  459. };
  460. static const StreamType HDMV_types[] = {
  461. { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
  462. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  463. { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  464. { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
  465. { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  466. { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
  467. { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
  468. { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
  469. { 0 },
  470. };
  471. /* ATSC ? */
  472. static const StreamType MISC_types[] = {
  473. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  474. { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  475. { 0 },
  476. };
  477. static const StreamType REGD_types[] = {
  478. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  479. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  480. { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
  481. { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  482. { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  483. { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  484. { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  485. { 0 },
  486. };
  487. /* descriptor present */
  488. static const StreamType DESC_types[] = {
  489. { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
  490. { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  491. { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  492. { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
  493. { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  494. { 0 },
  495. };
  496. static void mpegts_find_stream_type(AVStream *st,
  497. uint32_t stream_type, const StreamType *types)
  498. {
  499. for (; types->stream_type; types++) {
  500. if (stream_type == types->stream_type) {
  501. st->codec->codec_type = types->codec_type;
  502. st->codec->codec_id = types->codec_id;
  503. return;
  504. }
  505. }
  506. }
  507. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  508. uint32_t stream_type, uint32_t prog_reg_desc)
  509. {
  510. avpriv_set_pts_info(st, 33, 1, 90000);
  511. st->priv_data = pes;
  512. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  513. st->codec->codec_id = AV_CODEC_ID_NONE;
  514. st->need_parsing = AVSTREAM_PARSE_FULL;
  515. pes->st = st;
  516. pes->stream_type = stream_type;
  517. av_log(pes->stream, AV_LOG_DEBUG,
  518. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  519. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  520. st->codec->codec_tag = pes->stream_type;
  521. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  522. if (prog_reg_desc == AV_RL32("HDMV") &&
  523. st->codec->codec_id == AV_CODEC_ID_NONE) {
  524. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  525. if (pes->stream_type == 0x83) {
  526. // HDMV TrueHD streams also contain an AC3 coded version of the
  527. // audio track - add a second stream for this
  528. AVStream *sub_st;
  529. // priv_data cannot be shared between streams
  530. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  531. if (!sub_pes)
  532. return AVERROR(ENOMEM);
  533. memcpy(sub_pes, pes, sizeof(*sub_pes));
  534. sub_st = avformat_new_stream(pes->stream, NULL);
  535. if (!sub_st) {
  536. av_free(sub_pes);
  537. return AVERROR(ENOMEM);
  538. }
  539. sub_st->id = pes->pid;
  540. avpriv_set_pts_info(sub_st, 33, 1, 90000);
  541. sub_st->priv_data = sub_pes;
  542. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  543. sub_st->codec->codec_id = AV_CODEC_ID_AC3;
  544. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  545. sub_pes->sub_st = pes->sub_st = sub_st;
  546. }
  547. }
  548. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  549. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  550. return 0;
  551. }
  552. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  553. {
  554. av_init_packet(pkt);
  555. pkt->buf = pes->buffer;
  556. pkt->data = pes->buffer->data;
  557. pkt->size = pes->data_index;
  558. if(pes->total_size != MAX_PES_PAYLOAD &&
  559. pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
  560. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  561. pes->flags |= AV_PKT_FLAG_CORRUPT;
  562. }
  563. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  564. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  565. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  566. pkt->stream_index = pes->sub_st->index;
  567. else
  568. pkt->stream_index = pes->st->index;
  569. pkt->pts = pes->pts;
  570. pkt->dts = pes->dts;
  571. /* store position of first TS packet of this PES packet */
  572. pkt->pos = pes->ts_packet_pos;
  573. pkt->flags = pes->flags;
  574. /* reset pts values */
  575. pes->pts = AV_NOPTS_VALUE;
  576. pes->dts = AV_NOPTS_VALUE;
  577. pes->buffer = NULL;
  578. pes->data_index = 0;
  579. pes->flags = 0;
  580. }
  581. static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
  582. {
  583. GetBitContext gb;
  584. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  585. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  586. int dts_flag = -1, cts_flag = -1;
  587. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  588. init_get_bits(&gb, buf, buf_size*8);
  589. if (sl->use_au_start)
  590. au_start_flag = get_bits1(&gb);
  591. if (sl->use_au_end)
  592. au_end_flag = get_bits1(&gb);
  593. if (!sl->use_au_start && !sl->use_au_end)
  594. au_start_flag = au_end_flag = 1;
  595. if (sl->ocr_len > 0)
  596. ocr_flag = get_bits1(&gb);
  597. if (sl->use_idle)
  598. idle_flag = get_bits1(&gb);
  599. if (sl->use_padding)
  600. padding_flag = get_bits1(&gb);
  601. if (padding_flag)
  602. padding_bits = get_bits(&gb, 3);
  603. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  604. if (sl->packet_seq_num_len)
  605. skip_bits_long(&gb, sl->packet_seq_num_len);
  606. if (sl->degr_prior_len)
  607. if (get_bits1(&gb))
  608. skip_bits(&gb, sl->degr_prior_len);
  609. if (ocr_flag)
  610. skip_bits_long(&gb, sl->ocr_len);
  611. if (au_start_flag) {
  612. if (sl->use_rand_acc_pt)
  613. get_bits1(&gb);
  614. if (sl->au_seq_num_len > 0)
  615. skip_bits_long(&gb, sl->au_seq_num_len);
  616. if (sl->use_timestamps) {
  617. dts_flag = get_bits1(&gb);
  618. cts_flag = get_bits1(&gb);
  619. }
  620. }
  621. if (sl->inst_bitrate_len)
  622. inst_bitrate_flag = get_bits1(&gb);
  623. if (dts_flag == 1)
  624. dts = get_bits64(&gb, sl->timestamp_len);
  625. if (cts_flag == 1)
  626. cts = get_bits64(&gb, sl->timestamp_len);
  627. if (sl->au_len > 0)
  628. skip_bits_long(&gb, sl->au_len);
  629. if (inst_bitrate_flag)
  630. skip_bits_long(&gb, sl->inst_bitrate_len);
  631. }
  632. if (dts != AV_NOPTS_VALUE)
  633. pes->dts = dts;
  634. if (cts != AV_NOPTS_VALUE)
  635. pes->pts = cts;
  636. if (sl->timestamp_len && sl->timestamp_res)
  637. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  638. return (get_bits_count(&gb) + 7) >> 3;
  639. }
  640. /* return non zero if a packet could be constructed */
  641. static int mpegts_push_data(MpegTSFilter *filter,
  642. const uint8_t *buf, int buf_size, int is_start,
  643. int64_t pos)
  644. {
  645. PESContext *pes = filter->u.pes_filter.opaque;
  646. MpegTSContext *ts = pes->ts;
  647. const uint8_t *p;
  648. int len, code;
  649. if(!ts->pkt)
  650. return 0;
  651. if (is_start) {
  652. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  653. new_pes_packet(pes, ts->pkt);
  654. ts->stop_parse = 1;
  655. }
  656. pes->state = MPEGTS_HEADER;
  657. pes->data_index = 0;
  658. pes->ts_packet_pos = pos;
  659. }
  660. p = buf;
  661. while (buf_size > 0) {
  662. switch(pes->state) {
  663. case MPEGTS_HEADER:
  664. len = PES_START_SIZE - pes->data_index;
  665. if (len > buf_size)
  666. len = buf_size;
  667. memcpy(pes->header + pes->data_index, p, len);
  668. pes->data_index += len;
  669. p += len;
  670. buf_size -= len;
  671. if (pes->data_index == PES_START_SIZE) {
  672. /* we got all the PES or section header. We can now
  673. decide */
  674. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  675. pes->header[2] == 0x01) {
  676. /* it must be an mpeg2 PES stream */
  677. code = pes->header[3] | 0x100;
  678. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  679. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  680. (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
  681. code == 0x1be) /* padding_stream */
  682. goto skip;
  683. /* stream not present in PMT */
  684. if (!pes->st) {
  685. pes->st = avformat_new_stream(ts->stream, NULL);
  686. if (!pes->st)
  687. return AVERROR(ENOMEM);
  688. pes->st->id = pes->pid;
  689. mpegts_set_stream_info(pes->st, pes, 0, 0);
  690. }
  691. pes->total_size = AV_RB16(pes->header + 4);
  692. /* NOTE: a zero total size means the PES size is
  693. unbounded */
  694. if (!pes->total_size)
  695. pes->total_size = MAX_PES_PAYLOAD;
  696. /* allocate pes buffer */
  697. pes->buffer = av_buffer_alloc(pes->total_size +
  698. FF_INPUT_BUFFER_PADDING_SIZE);
  699. if (!pes->buffer)
  700. return AVERROR(ENOMEM);
  701. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  702. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  703. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  704. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  705. pes->state = MPEGTS_PESHEADER;
  706. if (pes->st->codec->codec_id == AV_CODEC_ID_NONE) {
  707. av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
  708. pes->pid, pes->stream_type);
  709. pes->st->codec->codec_id = AV_CODEC_ID_PROBE;
  710. }
  711. } else {
  712. pes->state = MPEGTS_PAYLOAD;
  713. pes->data_index = 0;
  714. }
  715. } else {
  716. /* otherwise, it should be a table */
  717. /* skip packet */
  718. skip:
  719. pes->state = MPEGTS_SKIP;
  720. continue;
  721. }
  722. }
  723. break;
  724. /**********************************************/
  725. /* PES packing parsing */
  726. case MPEGTS_PESHEADER:
  727. len = PES_HEADER_SIZE - pes->data_index;
  728. if (len < 0)
  729. return -1;
  730. if (len > buf_size)
  731. len = buf_size;
  732. memcpy(pes->header + pes->data_index, p, len);
  733. pes->data_index += len;
  734. p += len;
  735. buf_size -= len;
  736. if (pes->data_index == PES_HEADER_SIZE) {
  737. pes->pes_header_size = pes->header[8] + 9;
  738. pes->state = MPEGTS_PESHEADER_FILL;
  739. }
  740. break;
  741. case MPEGTS_PESHEADER_FILL:
  742. len = pes->pes_header_size - pes->data_index;
  743. if (len < 0)
  744. return -1;
  745. if (len > buf_size)
  746. len = buf_size;
  747. memcpy(pes->header + pes->data_index, p, len);
  748. pes->data_index += len;
  749. p += len;
  750. buf_size -= len;
  751. if (pes->data_index == pes->pes_header_size) {
  752. const uint8_t *r;
  753. unsigned int flags, pes_ext, skip;
  754. flags = pes->header[7];
  755. r = pes->header + 9;
  756. pes->pts = AV_NOPTS_VALUE;
  757. pes->dts = AV_NOPTS_VALUE;
  758. if ((flags & 0xc0) == 0x80) {
  759. pes->dts = pes->pts = ff_parse_pes_pts(r);
  760. r += 5;
  761. } else if ((flags & 0xc0) == 0xc0) {
  762. pes->pts = ff_parse_pes_pts(r);
  763. r += 5;
  764. pes->dts = ff_parse_pes_pts(r);
  765. r += 5;
  766. }
  767. pes->extended_stream_id = -1;
  768. if (flags & 0x01) { /* PES extension */
  769. pes_ext = *r++;
  770. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  771. skip = (pes_ext >> 4) & 0xb;
  772. skip += skip & 0x9;
  773. r += skip;
  774. if ((pes_ext & 0x41) == 0x01 &&
  775. (r + 2) <= (pes->header + pes->pes_header_size)) {
  776. /* PES extension 2 */
  777. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  778. pes->extended_stream_id = r[1];
  779. }
  780. }
  781. /* we got the full header. We parse it and get the payload */
  782. pes->state = MPEGTS_PAYLOAD;
  783. pes->data_index = 0;
  784. if (pes->stream_type == 0x12 && buf_size > 0) {
  785. int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
  786. pes->pes_header_size += sl_header_bytes;
  787. p += sl_header_bytes;
  788. buf_size -= sl_header_bytes;
  789. }
  790. }
  791. break;
  792. case MPEGTS_PAYLOAD:
  793. if (buf_size > 0 && pes->buffer) {
  794. if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
  795. new_pes_packet(pes, ts->pkt);
  796. pes->total_size = MAX_PES_PAYLOAD;
  797. pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
  798. if (!pes->buffer)
  799. return AVERROR(ENOMEM);
  800. ts->stop_parse = 1;
  801. } else if (pes->data_index == 0 && buf_size > pes->total_size) {
  802. // pes packet size is < ts size packet and pes data is padded with 0xff
  803. // not sure if this is legal in ts but see issue #2392
  804. buf_size = pes->total_size;
  805. }
  806. memcpy(pes->buffer->data + pes->data_index, p, buf_size);
  807. pes->data_index += buf_size;
  808. }
  809. buf_size = 0;
  810. /* emit complete packets with known packet size
  811. * decreases demuxer delay for infrequent packets like subtitles from
  812. * a couple of seconds to milliseconds for properly muxed files.
  813. * total_size is the number of bytes following pes_packet_length
  814. * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
  815. if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  816. pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
  817. ts->stop_parse = 1;
  818. new_pes_packet(pes, ts->pkt);
  819. }
  820. break;
  821. case MPEGTS_SKIP:
  822. buf_size = 0;
  823. break;
  824. }
  825. }
  826. return 0;
  827. }
  828. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  829. {
  830. MpegTSFilter *tss;
  831. PESContext *pes;
  832. /* if no pid found, then add a pid context */
  833. pes = av_mallocz(sizeof(PESContext));
  834. if (!pes)
  835. return 0;
  836. pes->ts = ts;
  837. pes->stream = ts->stream;
  838. pes->pid = pid;
  839. pes->pcr_pid = pcr_pid;
  840. pes->state = MPEGTS_SKIP;
  841. pes->pts = AV_NOPTS_VALUE;
  842. pes->dts = AV_NOPTS_VALUE;
  843. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  844. if (!tss) {
  845. av_free(pes);
  846. return 0;
  847. }
  848. return pes;
  849. }
  850. #define MAX_LEVEL 4
  851. typedef struct {
  852. AVFormatContext *s;
  853. AVIOContext pb;
  854. Mp4Descr *descr;
  855. Mp4Descr *active_descr;
  856. int descr_count;
  857. int max_descr_count;
  858. int level;
  859. } MP4DescrParseContext;
  860. static int init_MP4DescrParseContext(
  861. MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
  862. unsigned size, Mp4Descr *descr, int max_descr_count)
  863. {
  864. int ret;
  865. if (size > (1<<30))
  866. return AVERROR_INVALIDDATA;
  867. if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
  868. NULL, NULL, NULL, NULL)) < 0)
  869. return ret;
  870. d->s = s;
  871. d->level = 0;
  872. d->descr_count = 0;
  873. d->descr = descr;
  874. d->active_descr = NULL;
  875. d->max_descr_count = max_descr_count;
  876. return 0;
  877. }
  878. static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
  879. int64_t new_off = avio_tell(pb);
  880. (*len) -= new_off - *off;
  881. *off = new_off;
  882. }
  883. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  884. int target_tag);
  885. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  886. {
  887. while (len > 0) {
  888. if (parse_mp4_descr(d, off, len, 0) < 0)
  889. return -1;
  890. update_offsets(&d->pb, &off, &len);
  891. }
  892. return 0;
  893. }
  894. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  895. {
  896. avio_rb16(&d->pb); // ID
  897. avio_r8(&d->pb);
  898. avio_r8(&d->pb);
  899. avio_r8(&d->pb);
  900. avio_r8(&d->pb);
  901. avio_r8(&d->pb);
  902. update_offsets(&d->pb, &off, &len);
  903. return parse_mp4_descr_arr(d, off, len);
  904. }
  905. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  906. {
  907. int id_flags;
  908. if (len < 2)
  909. return 0;
  910. id_flags = avio_rb16(&d->pb);
  911. if (!(id_flags & 0x0020)) { //URL_Flag
  912. update_offsets(&d->pb, &off, &len);
  913. return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
  914. } else {
  915. return 0;
  916. }
  917. }
  918. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  919. {
  920. int es_id = 0;
  921. if (d->descr_count >= d->max_descr_count)
  922. return -1;
  923. ff_mp4_parse_es_descr(&d->pb, &es_id);
  924. d->active_descr = d->descr + (d->descr_count++);
  925. d->active_descr->es_id = es_id;
  926. update_offsets(&d->pb, &off, &len);
  927. parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  928. update_offsets(&d->pb, &off, &len);
  929. if (len > 0)
  930. parse_mp4_descr(d, off, len, MP4SLDescrTag);
  931. d->active_descr = NULL;
  932. return 0;
  933. }
  934. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  935. {
  936. Mp4Descr *descr = d->active_descr;
  937. if (!descr)
  938. return -1;
  939. d->active_descr->dec_config_descr = av_malloc(len);
  940. if (!descr->dec_config_descr)
  941. return AVERROR(ENOMEM);
  942. descr->dec_config_descr_len = len;
  943. avio_read(&d->pb, descr->dec_config_descr, len);
  944. return 0;
  945. }
  946. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  947. {
  948. Mp4Descr *descr = d->active_descr;
  949. int predefined;
  950. if (!descr)
  951. return -1;
  952. predefined = avio_r8(&d->pb);
  953. if (!predefined) {
  954. int lengths;
  955. int flags = avio_r8(&d->pb);
  956. descr->sl.use_au_start = !!(flags & 0x80);
  957. descr->sl.use_au_end = !!(flags & 0x40);
  958. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  959. descr->sl.use_padding = !!(flags & 0x08);
  960. descr->sl.use_timestamps = !!(flags & 0x04);
  961. descr->sl.use_idle = !!(flags & 0x02);
  962. descr->sl.timestamp_res = avio_rb32(&d->pb);
  963. avio_rb32(&d->pb);
  964. descr->sl.timestamp_len = avio_r8(&d->pb);
  965. descr->sl.ocr_len = avio_r8(&d->pb);
  966. descr->sl.au_len = avio_r8(&d->pb);
  967. descr->sl.inst_bitrate_len = avio_r8(&d->pb);
  968. lengths = avio_rb16(&d->pb);
  969. descr->sl.degr_prior_len = lengths >> 12;
  970. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  971. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  972. } else {
  973. av_log_missing_feature(d->s, "Predefined SLConfigDescriptor\n", 0);
  974. }
  975. return 0;
  976. }
  977. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  978. int target_tag) {
  979. int tag;
  980. int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  981. update_offsets(&d->pb, &off, &len);
  982. if (len < 0 || len1 > len || len1 <= 0) {
  983. av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
  984. return -1;
  985. }
  986. if (d->level++ >= MAX_LEVEL) {
  987. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  988. goto done;
  989. }
  990. if (target_tag && tag != target_tag) {
  991. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
  992. goto done;
  993. }
  994. switch (tag) {
  995. case MP4IODescrTag:
  996. parse_MP4IODescrTag(d, off, len1);
  997. break;
  998. case MP4ODescrTag:
  999. parse_MP4ODescrTag(d, off, len1);
  1000. break;
  1001. case MP4ESDescrTag:
  1002. parse_MP4ESDescrTag(d, off, len1);
  1003. break;
  1004. case MP4DecConfigDescrTag:
  1005. parse_MP4DecConfigDescrTag(d, off, len1);
  1006. break;
  1007. case MP4SLDescrTag:
  1008. parse_MP4SLDescrTag(d, off, len1);
  1009. break;
  1010. }
  1011. done:
  1012. d->level--;
  1013. avio_seek(&d->pb, off + len1, SEEK_SET);
  1014. return 0;
  1015. }
  1016. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1017. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1018. {
  1019. MP4DescrParseContext d;
  1020. if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1021. return -1;
  1022. parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1023. *descr_count = d.descr_count;
  1024. return 0;
  1025. }
  1026. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1027. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1028. {
  1029. MP4DescrParseContext d;
  1030. if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1031. return -1;
  1032. parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1033. *descr_count = d.descr_count;
  1034. return 0;
  1035. }
  1036. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1037. {
  1038. MpegTSContext *ts = filter->u.section_filter.opaque;
  1039. SectionHeader h;
  1040. const uint8_t *p, *p_end;
  1041. AVIOContext pb;
  1042. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1043. int mp4_descr_count = 0;
  1044. int i, pid;
  1045. AVFormatContext *s = ts->stream;
  1046. p_end = section + section_len - 4;
  1047. p = section;
  1048. if (parse_section_header(&h, &p, p_end) < 0)
  1049. return;
  1050. if (h.tid != M4OD_TID)
  1051. return;
  1052. mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1053. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1054. if (!ts->pids[pid])
  1055. continue;
  1056. for (i = 0; i < mp4_descr_count; i++) {
  1057. PESContext *pes;
  1058. AVStream *st;
  1059. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1060. continue;
  1061. if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
  1062. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1063. continue;
  1064. }
  1065. pes = ts->pids[pid]->u.pes_filter.opaque;
  1066. st = pes->st;
  1067. if (!st) {
  1068. continue;
  1069. }
  1070. pes->sl = mp4_descr[i].sl;
  1071. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1072. mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1073. ff_mp4_read_dec_config_descr(s, st, &pb);
  1074. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1075. st->codec->extradata_size > 0)
  1076. st->need_parsing = 0;
  1077. if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1078. st->codec->extradata_size > 0)
  1079. st->need_parsing = 0;
  1080. if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1081. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
  1082. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1083. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
  1084. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1085. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
  1086. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1087. }
  1088. }
  1089. }
  1090. for (i = 0; i < mp4_descr_count; i++)
  1091. av_free(mp4_descr[i].dec_config_descr);
  1092. }
  1093. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1094. const uint8_t **pp, const uint8_t *desc_list_end,
  1095. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1096. MpegTSContext *ts)
  1097. {
  1098. const uint8_t *desc_end;
  1099. int desc_len, desc_tag, desc_es_id;
  1100. char language[252];
  1101. int i;
  1102. desc_tag = get8(pp, desc_list_end);
  1103. if (desc_tag < 0)
  1104. return -1;
  1105. desc_len = get8(pp, desc_list_end);
  1106. if (desc_len < 0)
  1107. return -1;
  1108. desc_end = *pp + desc_len;
  1109. if (desc_end > desc_list_end)
  1110. return -1;
  1111. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1112. if (st->codec->codec_id == AV_CODEC_ID_NONE &&
  1113. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1114. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1115. switch(desc_tag) {
  1116. case 0x1E: /* SL descriptor */
  1117. desc_es_id = get16(pp, desc_end);
  1118. if (ts && ts->pids[pid])
  1119. ts->pids[pid]->es_id = desc_es_id;
  1120. for (i = 0; i < mp4_descr_count; i++)
  1121. if (mp4_descr[i].dec_config_descr_len &&
  1122. mp4_descr[i].es_id == desc_es_id) {
  1123. AVIOContext pb;
  1124. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1125. mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1126. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1127. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1128. st->codec->extradata_size > 0)
  1129. st->need_parsing = 0;
  1130. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1131. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1132. }
  1133. break;
  1134. case 0x1F: /* FMC descriptor */
  1135. get16(pp, desc_end);
  1136. if (mp4_descr_count > 0 && st->codec->codec_id == AV_CODEC_ID_AAC_LATM &&
  1137. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1138. AVIOContext pb;
  1139. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1140. mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1141. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1142. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1143. st->codec->extradata_size > 0)
  1144. st->need_parsing = 0;
  1145. }
  1146. break;
  1147. case 0x56: /* DVB teletext descriptor */
  1148. language[0] = get8(pp, desc_end);
  1149. language[1] = get8(pp, desc_end);
  1150. language[2] = get8(pp, desc_end);
  1151. language[3] = 0;
  1152. av_dict_set(&st->metadata, "language", language, 0);
  1153. break;
  1154. case 0x59: /* subtitling descriptor */
  1155. language[0] = get8(pp, desc_end);
  1156. language[1] = get8(pp, desc_end);
  1157. language[2] = get8(pp, desc_end);
  1158. language[3] = 0;
  1159. /* hearing impaired subtitles detection */
  1160. switch(get8(pp, desc_end)) {
  1161. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1162. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1163. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1164. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1165. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1166. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1167. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1168. break;
  1169. }
  1170. if (st->codec->extradata) {
  1171. if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
  1172. av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
  1173. } else {
  1174. st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
  1175. if (st->codec->extradata) {
  1176. st->codec->extradata_size = 4;
  1177. memcpy(st->codec->extradata, *pp, 4);
  1178. }
  1179. }
  1180. *pp += 4;
  1181. av_dict_set(&st->metadata, "language", language, 0);
  1182. break;
  1183. case 0x0a: /* ISO 639 language descriptor */
  1184. for (i = 0; i + 4 <= desc_len; i += 4) {
  1185. language[i + 0] = get8(pp, desc_end);
  1186. language[i + 1] = get8(pp, desc_end);
  1187. language[i + 2] = get8(pp, desc_end);
  1188. language[i + 3] = ',';
  1189. switch (get8(pp, desc_end)) {
  1190. case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
  1191. case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
  1192. case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
  1193. }
  1194. }
  1195. if (i) {
  1196. language[i - 1] = 0;
  1197. av_dict_set(&st->metadata, "language", language, 0);
  1198. }
  1199. break;
  1200. case 0x05: /* registration descriptor */
  1201. st->codec->codec_tag = bytestream_get_le32(pp);
  1202. av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  1203. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1204. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1205. break;
  1206. default:
  1207. break;
  1208. }
  1209. *pp = desc_end;
  1210. return 0;
  1211. }
  1212. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1213. {
  1214. MpegTSContext *ts = filter->u.section_filter.opaque;
  1215. SectionHeader h1, *h = &h1;
  1216. PESContext *pes;
  1217. AVStream *st;
  1218. const uint8_t *p, *p_end, *desc_list_end;
  1219. int program_info_length, pcr_pid, pid, stream_type;
  1220. int desc_list_len;
  1221. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1222. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1223. int mp4_descr_count = 0;
  1224. int i;
  1225. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1226. hex_dump_debug(ts->stream, section, section_len);
  1227. p_end = section + section_len - 4;
  1228. p = section;
  1229. if (parse_section_header(h, &p, p_end) < 0)
  1230. return;
  1231. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1232. h->id, h->sec_num, h->last_sec_num);
  1233. if (h->tid != PMT_TID)
  1234. return;
  1235. clear_program(ts, h->id);
  1236. pcr_pid = get16(&p, p_end);
  1237. if (pcr_pid < 0)
  1238. return;
  1239. pcr_pid &= 0x1fff;
  1240. add_pid_to_pmt(ts, h->id, pcr_pid);
  1241. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1242. program_info_length = get16(&p, p_end);
  1243. if (program_info_length < 0)
  1244. return;
  1245. program_info_length &= 0xfff;
  1246. while(program_info_length >= 2) {
  1247. uint8_t tag, len;
  1248. tag = get8(&p, p_end);
  1249. len = get8(&p, p_end);
  1250. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1251. if(len > program_info_length - 2)
  1252. //something else is broken, exit the program_descriptors_loop
  1253. break;
  1254. program_info_length -= len + 2;
  1255. if (tag == 0x1d) { // IOD descriptor
  1256. get8(&p, p_end); // scope
  1257. get8(&p, p_end); // label
  1258. len -= 2;
  1259. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1260. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1261. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1262. prog_reg_desc = bytestream_get_le32(&p);
  1263. len -= 4;
  1264. }
  1265. p += len;
  1266. }
  1267. p += program_info_length;
  1268. if (p >= p_end)
  1269. goto out;
  1270. // stop parsing after pmt, we found header
  1271. if (!ts->stream->nb_streams)
  1272. ts->stop_parse = 1;
  1273. for(;;) {
  1274. st = 0;
  1275. pes = NULL;
  1276. stream_type = get8(&p, p_end);
  1277. if (stream_type < 0)
  1278. break;
  1279. pid = get16(&p, p_end);
  1280. if (pid < 0)
  1281. break;
  1282. pid &= 0x1fff;
  1283. /* now create stream */
  1284. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1285. pes = ts->pids[pid]->u.pes_filter.opaque;
  1286. if (!pes->st) {
  1287. pes->st = avformat_new_stream(pes->stream, NULL);
  1288. pes->st->id = pes->pid;
  1289. }
  1290. st = pes->st;
  1291. } else if (stream_type != 0x13) {
  1292. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  1293. pes = add_pes_stream(ts, pid, pcr_pid);
  1294. if (pes) {
  1295. st = avformat_new_stream(pes->stream, NULL);
  1296. st->id = pes->pid;
  1297. }
  1298. } else {
  1299. int idx = ff_find_stream_index(ts->stream, pid);
  1300. if (idx >= 0) {
  1301. st = ts->stream->streams[idx];
  1302. } else {
  1303. st = avformat_new_stream(ts->stream, NULL);
  1304. st->id = pid;
  1305. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1306. }
  1307. }
  1308. if (!st)
  1309. goto out;
  1310. if (pes && !pes->stream_type)
  1311. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1312. add_pid_to_pmt(ts, h->id, pid);
  1313. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1314. desc_list_len = get16(&p, p_end);
  1315. if (desc_list_len < 0)
  1316. break;
  1317. desc_list_len &= 0xfff;
  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, 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);
  1356. if (pmt_pid < 0)
  1357. break;
  1358. pmt_pid &= 0x1fff;
  1359. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1360. if (sid == 0x0000) {
  1361. /* NIT info */
  1362. } else {
  1363. av_new_program(ts->stream, sid);
  1364. if (ts->pids[pmt_pid])
  1365. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1366. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1367. add_pat_entry(ts, sid);
  1368. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  1369. add_pid_to_pmt(ts, sid, pmt_pid);
  1370. }
  1371. }
  1372. }
  1373. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1374. {
  1375. MpegTSContext *ts = filter->u.section_filter.opaque;
  1376. SectionHeader h1, *h = &h1;
  1377. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1378. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1379. char *name, *provider_name;
  1380. av_dlog(ts->stream, "SDT:\n");
  1381. hex_dump_debug(ts->stream, section, section_len);
  1382. p_end = section + section_len - 4;
  1383. p = section;
  1384. if (parse_section_header(h, &p, p_end) < 0)
  1385. return;
  1386. if (h->tid != SDT_TID)
  1387. return;
  1388. onid = get16(&p, p_end);
  1389. if (onid < 0)
  1390. return;
  1391. val = get8(&p, p_end);
  1392. if (val < 0)
  1393. return;
  1394. for(;;) {
  1395. sid = get16(&p, p_end);
  1396. if (sid < 0)
  1397. break;
  1398. val = get8(&p, p_end);
  1399. if (val < 0)
  1400. break;
  1401. desc_list_len = get16(&p, p_end);
  1402. if (desc_list_len < 0)
  1403. break;
  1404. desc_list_len &= 0xfff;
  1405. desc_list_end = p + desc_list_len;
  1406. if (desc_list_end > p_end)
  1407. break;
  1408. for(;;) {
  1409. desc_tag = get8(&p, desc_list_end);
  1410. if (desc_tag < 0)
  1411. break;
  1412. desc_len = get8(&p, desc_list_end);
  1413. desc_end = p + desc_len;
  1414. if (desc_end > desc_list_end)
  1415. break;
  1416. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1417. desc_tag, desc_len);
  1418. switch(desc_tag) {
  1419. case 0x48:
  1420. service_type = get8(&p, p_end);
  1421. if (service_type < 0)
  1422. break;
  1423. provider_name = getstr8(&p, p_end);
  1424. if (!provider_name)
  1425. break;
  1426. name = getstr8(&p, p_end);
  1427. if (name) {
  1428. AVProgram *program = av_new_program(ts->stream, sid);
  1429. if(program) {
  1430. av_dict_set(&program->metadata, "service_name", name, 0);
  1431. av_dict_set(&program->metadata, "service_provider", provider_name, 0);
  1432. }
  1433. }
  1434. av_free(name);
  1435. av_free(provider_name);
  1436. break;
  1437. default:
  1438. break;
  1439. }
  1440. p = desc_end;
  1441. }
  1442. p = desc_list_end;
  1443. }
  1444. }
  1445. /* handle one TS packet */
  1446. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1447. {
  1448. AVFormatContext *s = ts->stream;
  1449. MpegTSFilter *tss;
  1450. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1451. has_adaptation, has_payload;
  1452. const uint8_t *p, *p_end;
  1453. int64_t pos;
  1454. pid = AV_RB16(packet + 1) & 0x1fff;
  1455. if(pid && discard_pid(ts, pid))
  1456. return 0;
  1457. is_start = packet[1] & 0x40;
  1458. tss = ts->pids[pid];
  1459. if (ts->auto_guess && tss == NULL && is_start) {
  1460. add_pes_stream(ts, pid, -1);
  1461. tss = ts->pids[pid];
  1462. }
  1463. if (!tss)
  1464. return 0;
  1465. afc = (packet[3] >> 4) & 3;
  1466. if (afc == 0) /* reserved value */
  1467. return 0;
  1468. has_adaptation = afc & 2;
  1469. has_payload = afc & 1;
  1470. is_discontinuity = has_adaptation
  1471. && packet[4] != 0 /* with length > 0 */
  1472. && (packet[5] & 0x80); /* and discontinuity indicated */
  1473. /* continuity check (currently not used) */
  1474. cc = (packet[3] & 0xf);
  1475. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1476. cc_ok = pid == 0x1FFF // null packet PID
  1477. || is_discontinuity
  1478. || tss->last_cc < 0
  1479. || expected_cc == cc;
  1480. tss->last_cc = cc;
  1481. if (!cc_ok) {
  1482. av_log(ts->stream, AV_LOG_WARNING,
  1483. "Continuity check failed for pid %d expected %d got %d\n",
  1484. pid, expected_cc, cc);
  1485. if(tss->type == MPEGTS_PES) {
  1486. PESContext *pc = tss->u.pes_filter.opaque;
  1487. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1488. }
  1489. }
  1490. if (!has_payload)
  1491. return 0;
  1492. p = packet + 4;
  1493. if (has_adaptation) {
  1494. /* skip adaptation field */
  1495. p += p[0] + 1;
  1496. }
  1497. /* if past the end of packet, ignore */
  1498. p_end = packet + TS_PACKET_SIZE;
  1499. if (p >= p_end)
  1500. return 0;
  1501. pos = avio_tell(ts->stream->pb);
  1502. ts->pos47= pos % ts->raw_packet_size;
  1503. if (tss->type == MPEGTS_SECTION) {
  1504. if (is_start) {
  1505. /* pointer field present */
  1506. len = *p++;
  1507. if (p + len > p_end)
  1508. return 0;
  1509. if (len && cc_ok) {
  1510. /* write remaining section bytes */
  1511. write_section_data(s, tss,
  1512. p, len, 0);
  1513. /* check whether filter has been closed */
  1514. if (!ts->pids[pid])
  1515. return 0;
  1516. }
  1517. p += len;
  1518. if (p < p_end) {
  1519. write_section_data(s, tss,
  1520. p, p_end - p, 1);
  1521. }
  1522. } else {
  1523. if (cc_ok) {
  1524. write_section_data(s, tss,
  1525. p, p_end - p, 0);
  1526. }
  1527. }
  1528. } else {
  1529. int ret;
  1530. // Note: The position here points actually behind the current packet.
  1531. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1532. pos - ts->raw_packet_size)) < 0)
  1533. return ret;
  1534. }
  1535. return 0;
  1536. }
  1537. /* XXX: try to find a better synchro over several packets (use
  1538. get_packet_size() ?) */
  1539. static int mpegts_resync(AVFormatContext *s)
  1540. {
  1541. AVIOContext *pb = s->pb;
  1542. int c, i;
  1543. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1544. c = avio_r8(pb);
  1545. if (pb->eof_reached)
  1546. return -1;
  1547. if (c == 0x47) {
  1548. avio_seek(pb, -1, SEEK_CUR);
  1549. return 0;
  1550. }
  1551. }
  1552. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1553. /* no sync found */
  1554. return -1;
  1555. }
  1556. /* return -1 if error or EOF. Return 0 if OK. */
  1557. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1558. {
  1559. AVIOContext *pb = s->pb;
  1560. int skip, len;
  1561. for(;;) {
  1562. len = avio_read(pb, buf, TS_PACKET_SIZE);
  1563. if (len != TS_PACKET_SIZE)
  1564. return len < 0 ? len : AVERROR_EOF;
  1565. /* check packet sync byte */
  1566. if (buf[0] != 0x47) {
  1567. /* find a new packet start */
  1568. avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1569. if (mpegts_resync(s) < 0)
  1570. return AVERROR(EAGAIN);
  1571. else
  1572. continue;
  1573. } else {
  1574. skip = raw_packet_size - TS_PACKET_SIZE;
  1575. if (skip > 0)
  1576. avio_skip(pb, skip);
  1577. break;
  1578. }
  1579. }
  1580. return 0;
  1581. }
  1582. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1583. {
  1584. AVFormatContext *s = ts->stream;
  1585. uint8_t packet[TS_PACKET_SIZE+FF_INPUT_BUFFER_PADDING_SIZE];
  1586. int packet_num, ret = 0;
  1587. if (avio_tell(s->pb) != ts->last_pos) {
  1588. int i;
  1589. av_dlog(ts->stream, "Skipping after seek\n");
  1590. /* seek detected, flush pes buffer */
  1591. for (i = 0; i < NB_PID_MAX; i++) {
  1592. if (ts->pids[i]) {
  1593. if (ts->pids[i]->type == MPEGTS_PES) {
  1594. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1595. av_buffer_unref(&pes->buffer);
  1596. pes->data_index = 0;
  1597. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1598. }
  1599. ts->pids[i]->last_cc = -1;
  1600. }
  1601. }
  1602. }
  1603. ts->stop_parse = 0;
  1604. packet_num = 0;
  1605. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  1606. for(;;) {
  1607. if (ts->stop_parse>0)
  1608. break;
  1609. packet_num++;
  1610. if (nb_packets != 0 && packet_num >= nb_packets)
  1611. break;
  1612. ret = read_packet(s, packet, ts->raw_packet_size);
  1613. if (ret != 0)
  1614. break;
  1615. ret = handle_packet(ts, packet);
  1616. if (ret != 0)
  1617. break;
  1618. }
  1619. ts->last_pos = avio_tell(s->pb);
  1620. return ret;
  1621. }
  1622. static int mpegts_probe(AVProbeData *p)
  1623. {
  1624. const int size= p->buf_size;
  1625. int score, fec_score, dvhs_score;
  1626. int check_count= size / TS_FEC_PACKET_SIZE;
  1627. #define CHECK_COUNT 10
  1628. if (check_count < CHECK_COUNT)
  1629. return -1;
  1630. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1631. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1632. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1633. av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  1634. score, dvhs_score, fec_score);
  1635. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1636. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1637. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1638. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1639. else return -1;
  1640. }
  1641. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1642. (-1) if not available */
  1643. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1644. const uint8_t *packet)
  1645. {
  1646. int afc, len, flags;
  1647. const uint8_t *p;
  1648. unsigned int v;
  1649. afc = (packet[3] >> 4) & 3;
  1650. if (afc <= 1)
  1651. return -1;
  1652. p = packet + 4;
  1653. len = p[0];
  1654. p++;
  1655. if (len == 0)
  1656. return -1;
  1657. flags = *p++;
  1658. len--;
  1659. if (!(flags & 0x10))
  1660. return -1;
  1661. if (len < 6)
  1662. return -1;
  1663. v = AV_RB32(p);
  1664. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1665. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1666. return 0;
  1667. }
  1668. static int mpegts_read_header(AVFormatContext *s)
  1669. {
  1670. MpegTSContext *ts = s->priv_data;
  1671. AVIOContext *pb = s->pb;
  1672. uint8_t buf[5*1024];
  1673. int len;
  1674. int64_t pos;
  1675. /* read the first 1024 bytes to get packet size */
  1676. pos = avio_tell(pb);
  1677. len = avio_read(pb, buf, sizeof(buf));
  1678. if (len != sizeof(buf))
  1679. goto fail;
  1680. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1681. if (ts->raw_packet_size <= 0)
  1682. goto fail;
  1683. ts->stream = s;
  1684. ts->auto_guess = 0;
  1685. if (s->iformat == &ff_mpegts_demuxer) {
  1686. /* normal demux */
  1687. /* first do a scan to get all the services */
  1688. if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
  1689. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1690. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1691. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1692. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1693. /* if could not find service, enable auto_guess */
  1694. ts->auto_guess = 1;
  1695. av_dlog(ts->stream, "tuning done\n");
  1696. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1697. } else {
  1698. AVStream *st;
  1699. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1700. int64_t pcrs[2], pcr_h;
  1701. int packet_count[2];
  1702. uint8_t packet[TS_PACKET_SIZE];
  1703. /* only read packets */
  1704. st = avformat_new_stream(s, NULL);
  1705. if (!st)
  1706. goto fail;
  1707. avpriv_set_pts_info(st, 60, 1, 27000000);
  1708. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1709. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  1710. /* we iterate until we find two PCRs to estimate the bitrate */
  1711. pcr_pid = -1;
  1712. nb_pcrs = 0;
  1713. nb_packets = 0;
  1714. for(;;) {
  1715. ret = read_packet(s, packet, ts->raw_packet_size);
  1716. if (ret < 0)
  1717. return -1;
  1718. pid = AV_RB16(packet + 1) & 0x1fff;
  1719. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1720. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1721. pcr_pid = pid;
  1722. packet_count[nb_pcrs] = nb_packets;
  1723. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1724. nb_pcrs++;
  1725. if (nb_pcrs >= 2)
  1726. break;
  1727. }
  1728. nb_packets++;
  1729. }
  1730. /* NOTE1: the bitrate is computed without the FEC */
  1731. /* NOTE2: it is only the bitrate of the start of the stream */
  1732. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1733. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1734. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1735. st->codec->bit_rate = s->bit_rate;
  1736. st->start_time = ts->cur_pcr;
  1737. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  1738. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1739. }
  1740. avio_seek(pb, pos, SEEK_SET);
  1741. return 0;
  1742. fail:
  1743. return -1;
  1744. }
  1745. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1746. static int mpegts_raw_read_packet(AVFormatContext *s,
  1747. AVPacket *pkt)
  1748. {
  1749. MpegTSContext *ts = s->priv_data;
  1750. int ret, i;
  1751. int64_t pcr_h, next_pcr_h, pos;
  1752. int pcr_l, next_pcr_l;
  1753. uint8_t pcr_buf[12];
  1754. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1755. return AVERROR(ENOMEM);
  1756. pkt->pos= avio_tell(s->pb);
  1757. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1758. if (ret < 0) {
  1759. av_free_packet(pkt);
  1760. return ret;
  1761. }
  1762. if (ts->mpeg2ts_compute_pcr) {
  1763. /* compute exact PCR for each packet */
  1764. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1765. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1766. pos = avio_tell(s->pb);
  1767. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1768. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1769. avio_read(s->pb, pcr_buf, 12);
  1770. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1771. /* XXX: not precise enough */
  1772. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1773. (i + 1);
  1774. break;
  1775. }
  1776. }
  1777. avio_seek(s->pb, pos, SEEK_SET);
  1778. /* no next PCR found: we use previous increment */
  1779. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1780. }
  1781. pkt->pts = ts->cur_pcr;
  1782. pkt->duration = ts->pcr_incr;
  1783. ts->cur_pcr += ts->pcr_incr;
  1784. }
  1785. pkt->stream_index = 0;
  1786. return 0;
  1787. }
  1788. static int mpegts_read_packet(AVFormatContext *s,
  1789. AVPacket *pkt)
  1790. {
  1791. MpegTSContext *ts = s->priv_data;
  1792. int ret, i;
  1793. pkt->size = -1;
  1794. ts->pkt = pkt;
  1795. ret = handle_packets(ts, 0);
  1796. if (ret < 0) {
  1797. /* flush pes data left */
  1798. for (i = 0; i < NB_PID_MAX; i++) {
  1799. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1800. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1801. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1802. new_pes_packet(pes, pkt);
  1803. pes->state = MPEGTS_SKIP;
  1804. ret = 0;
  1805. break;
  1806. }
  1807. }
  1808. }
  1809. }
  1810. if (!ret && pkt->size < 0)
  1811. ret = AVERROR(EINTR);
  1812. return ret;
  1813. }
  1814. static void mpegts_free(MpegTSContext *ts)
  1815. {
  1816. int i;
  1817. clear_programs(ts);
  1818. for(i=0;i<NB_PID_MAX;i++)
  1819. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1820. }
  1821. static int mpegts_read_close(AVFormatContext *s)
  1822. {
  1823. MpegTSContext *ts = s->priv_data;
  1824. mpegts_free(ts);
  1825. return 0;
  1826. }
  1827. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1828. int64_t *ppos, int64_t pos_limit)
  1829. {
  1830. MpegTSContext *ts = s->priv_data;
  1831. int64_t pos, timestamp;
  1832. uint8_t buf[TS_PACKET_SIZE];
  1833. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1834. const int find_next= 1;
  1835. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1836. if (find_next) {
  1837. for(;;) {
  1838. avio_seek(s->pb, pos, SEEK_SET);
  1839. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1840. return AV_NOPTS_VALUE;
  1841. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1842. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1843. break;
  1844. }
  1845. pos += ts->raw_packet_size;
  1846. }
  1847. } else {
  1848. for(;;) {
  1849. pos -= ts->raw_packet_size;
  1850. if (pos < 0)
  1851. return AV_NOPTS_VALUE;
  1852. avio_seek(s->pb, pos, SEEK_SET);
  1853. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1854. return AV_NOPTS_VALUE;
  1855. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1856. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1857. break;
  1858. }
  1859. }
  1860. }
  1861. *ppos = pos;
  1862. return timestamp;
  1863. }
  1864. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1865. MpegTSContext *ts = s->priv_data;
  1866. uint8_t buf[TS_PACKET_SIZE];
  1867. int64_t pos;
  1868. if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1869. return -1;
  1870. pos= avio_tell(s->pb);
  1871. for(;;) {
  1872. avio_seek(s->pb, pos, SEEK_SET);
  1873. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1874. return -1;
  1875. // pid = AV_RB16(buf + 1) & 0x1fff;
  1876. if(buf[1] & 0x40) break;
  1877. pos += ts->raw_packet_size;
  1878. }
  1879. avio_seek(s->pb, pos, SEEK_SET);
  1880. return 0;
  1881. }
  1882. /**************************************************************/
  1883. /* parsing functions - called from other demuxers such as RTP */
  1884. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1885. {
  1886. MpegTSContext *ts;
  1887. ts = av_mallocz(sizeof(MpegTSContext));
  1888. if (!ts)
  1889. return NULL;
  1890. /* no stream case, currently used by RTP */
  1891. ts->raw_packet_size = TS_PACKET_SIZE;
  1892. ts->stream = s;
  1893. ts->auto_guess = 1;
  1894. return ts;
  1895. }
  1896. /* return the consumed length if a packet was output, or -1 if no
  1897. packet is output */
  1898. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1899. const uint8_t *buf, int len)
  1900. {
  1901. int len1;
  1902. len1 = len;
  1903. ts->pkt = pkt;
  1904. ts->stop_parse = 0;
  1905. for(;;) {
  1906. if (ts->stop_parse>0)
  1907. break;
  1908. if (len < TS_PACKET_SIZE)
  1909. return -1;
  1910. if (buf[0] != 0x47) {
  1911. buf++;
  1912. len--;
  1913. } else {
  1914. handle_packet(ts, buf);
  1915. buf += TS_PACKET_SIZE;
  1916. len -= TS_PACKET_SIZE;
  1917. }
  1918. }
  1919. return len1 - len;
  1920. }
  1921. void ff_mpegts_parse_close(MpegTSContext *ts)
  1922. {
  1923. mpegts_free(ts);
  1924. av_free(ts);
  1925. }
  1926. AVInputFormat ff_mpegts_demuxer = {
  1927. .name = "mpegts",
  1928. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  1929. .priv_data_size = sizeof(MpegTSContext),
  1930. .read_probe = mpegts_probe,
  1931. .read_header = mpegts_read_header,
  1932. .read_packet = mpegts_read_packet,
  1933. .read_close = mpegts_read_close,
  1934. .read_seek = read_seek,
  1935. .read_timestamp = mpegts_get_pcr,
  1936. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  1937. };
  1938. AVInputFormat ff_mpegtsraw_demuxer = {
  1939. .name = "mpegtsraw",
  1940. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  1941. .priv_data_size = sizeof(MpegTSContext),
  1942. .read_header = mpegts_read_header,
  1943. .read_packet = mpegts_raw_read_packet,
  1944. .read_close = mpegts_read_close,
  1945. .read_seek = read_seek,
  1946. .read_timestamp = mpegts_get_pcr,
  1947. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  1948. .priv_class = &mpegtsraw_class,
  1949. };