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.

2185 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/crc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/log.h"
  24. #include "libavutil/dict.h"
  25. #include "libavutil/mathematics.h"
  26. #include "libavutil/opt.h"
  27. #include "libavcodec/bytestream.h"
  28. #include "libavcodec/get_bits.h"
  29. #include "avformat.h"
  30. #include "mpegts.h"
  31. #include "internal.h"
  32. #include "avio_internal.h"
  33. #include "seek.h"
  34. #include "mpeg.h"
  35. #include "isom.h"
  36. /* maximum size in which we look for synchronisation if
  37. synchronisation is lost */
  38. #define MAX_RESYNC_SIZE 65536
  39. #define MAX_PES_PAYLOAD 200*1024
  40. #define MAX_MP4_DESCR_COUNT 16
  41. enum MpegTSFilterType {
  42. MPEGTS_PES,
  43. MPEGTS_SECTION,
  44. };
  45. typedef struct MpegTSFilter MpegTSFilter;
  46. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
  47. typedef struct MpegTSPESFilter {
  48. PESCallback *pes_cb;
  49. void *opaque;
  50. } MpegTSPESFilter;
  51. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  52. typedef void SetServiceCallback(void *opaque, int ret);
  53. typedef struct MpegTSSectionFilter {
  54. int section_index;
  55. int section_h_size;
  56. uint8_t *section_buf;
  57. unsigned int check_crc:1;
  58. unsigned int end_of_section_reached:1;
  59. SectionCallback *section_cb;
  60. void *opaque;
  61. } MpegTSSectionFilter;
  62. struct MpegTSFilter {
  63. int pid;
  64. int es_id;
  65. int last_cc; /* last cc code (-1 if first packet) */
  66. enum MpegTSFilterType type;
  67. union {
  68. MpegTSPESFilter pes_filter;
  69. MpegTSSectionFilter section_filter;
  70. } u;
  71. };
  72. #define MAX_PIDS_PER_PROGRAM 64
  73. struct Program {
  74. unsigned int id; //program id/service id
  75. unsigned int nb_pids;
  76. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  77. };
  78. struct MpegTSContext {
  79. const AVClass *class;
  80. /* user data */
  81. AVFormatContext *stream;
  82. /** raw packet size, including FEC if present */
  83. int raw_packet_size;
  84. int pos47;
  85. /** if true, all pids are analyzed to find streams */
  86. int auto_guess;
  87. /** compute exact PCR for each transport stream packet */
  88. int mpeg2ts_compute_pcr;
  89. int64_t cur_pcr; /**< used to estimate the exact PCR */
  90. int pcr_incr; /**< used to estimate the exact PCR */
  91. /* data needed to handle file based ts */
  92. /** stop parsing loop */
  93. int stop_parse;
  94. /** packet containing Audio/Video data */
  95. AVPacket *pkt;
  96. /** to detect seek */
  97. int64_t last_pos;
  98. /******************************************/
  99. /* private mpegts data */
  100. /* scan context */
  101. /** structure to keep track of Program->pids mapping */
  102. unsigned int nb_prg;
  103. struct Program *prg;
  104. /** filters for various streams specified by PMT + for the PAT and PMT */
  105. MpegTSFilter *pids[NB_PID_MAX];
  106. };
  107. static const AVOption options[] = {
  108. {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
  109. {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  110. { NULL },
  111. };
  112. static const AVClass mpegtsraw_class = {
  113. .class_name = "mpegtsraw demuxer",
  114. .item_name = av_default_item_name,
  115. .option = options,
  116. .version = LIBAVUTIL_VERSION_INT,
  117. };
  118. /* TS stream handling */
  119. enum MpegTSState {
  120. MPEGTS_HEADER = 0,
  121. MPEGTS_PESHEADER,
  122. MPEGTS_PESHEADER_FILL,
  123. MPEGTS_PAYLOAD,
  124. MPEGTS_SKIP,
  125. };
  126. /* enough for PES header + length */
  127. #define PES_START_SIZE 6
  128. #define PES_HEADER_SIZE 9
  129. #define MAX_PES_HEADER_SIZE (9 + 255)
  130. typedef struct PESContext {
  131. int pid;
  132. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  133. int stream_type;
  134. MpegTSContext *ts;
  135. AVFormatContext *stream;
  136. AVStream *st;
  137. AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  138. enum MpegTSState state;
  139. /* used to get the format */
  140. int data_index;
  141. int flags; /**< copied to the AVPacket flags */
  142. int total_size;
  143. int pes_header_size;
  144. int extended_stream_id;
  145. int64_t pts, dts;
  146. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  147. uint8_t header[MAX_PES_HEADER_SIZE];
  148. uint8_t *buffer;
  149. SLConfigDescr sl;
  150. } PESContext;
  151. extern AVInputFormat ff_mpegts_demuxer;
  152. static void clear_program(MpegTSContext *ts, unsigned int programid)
  153. {
  154. int i;
  155. for(i=0; i<ts->nb_prg; i++)
  156. if(ts->prg[i].id == programid)
  157. ts->prg[i].nb_pids = 0;
  158. }
  159. static void clear_programs(MpegTSContext *ts)
  160. {
  161. av_freep(&ts->prg);
  162. ts->nb_prg=0;
  163. }
  164. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  165. {
  166. struct Program *p;
  167. void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
  168. if(!tmp)
  169. return;
  170. ts->prg = tmp;
  171. p = &ts->prg[ts->nb_prg];
  172. p->id = programid;
  173. p->nb_pids = 0;
  174. ts->nb_prg++;
  175. }
  176. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  177. {
  178. int i;
  179. struct Program *p = NULL;
  180. for(i=0; i<ts->nb_prg; i++) {
  181. if(ts->prg[i].id == programid) {
  182. p = &ts->prg[i];
  183. break;
  184. }
  185. }
  186. if(!p)
  187. return;
  188. if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  189. return;
  190. p->pids[p->nb_pids++] = pid;
  191. }
  192. /**
  193. * @brief discard_pid() decides if the pid is to be discarded according
  194. * to caller's programs selection
  195. * @param ts : - TS context
  196. * @param pid : - pid
  197. * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  198. * 0 otherwise
  199. */
  200. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  201. {
  202. int i, j, k;
  203. int used = 0, discarded = 0;
  204. struct Program *p;
  205. for(i=0; i<ts->nb_prg; i++) {
  206. p = &ts->prg[i];
  207. for(j=0; j<p->nb_pids; j++) {
  208. if(p->pids[j] != pid)
  209. continue;
  210. //is program with id p->id set to be discarded?
  211. for(k=0; k<ts->stream->nb_programs; k++) {
  212. if(ts->stream->programs[k]->id == p->id) {
  213. if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  214. discarded++;
  215. else
  216. used++;
  217. }
  218. }
  219. }
  220. }
  221. return !used && discarded;
  222. }
  223. /**
  224. * Assemble PES packets out of TS packets, and then call the "section_cb"
  225. * function when they are complete.
  226. */
  227. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  228. const uint8_t *buf, int buf_size, int is_start)
  229. {
  230. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  231. int len;
  232. if (is_start) {
  233. memcpy(tss->section_buf, buf, buf_size);
  234. tss->section_index = buf_size;
  235. tss->section_h_size = -1;
  236. tss->end_of_section_reached = 0;
  237. } else {
  238. if (tss->end_of_section_reached)
  239. return;
  240. len = 4096 - tss->section_index;
  241. if (buf_size < len)
  242. len = buf_size;
  243. memcpy(tss->section_buf + tss->section_index, buf, len);
  244. tss->section_index += len;
  245. }
  246. /* compute section length if possible */
  247. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  248. len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  249. if (len > 4096)
  250. return;
  251. tss->section_h_size = len;
  252. }
  253. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  254. tss->end_of_section_reached = 1;
  255. if (!tss->check_crc ||
  256. av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
  257. tss->section_buf, tss->section_h_size) == 0)
  258. tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  259. }
  260. }
  261. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  262. SectionCallback *section_cb, void *opaque,
  263. int check_crc)
  264. {
  265. MpegTSFilter *filter;
  266. MpegTSSectionFilter *sec;
  267. av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
  268. if (pid >= NB_PID_MAX || ts->pids[pid])
  269. return NULL;
  270. filter = av_mallocz(sizeof(MpegTSFilter));
  271. if (!filter)
  272. return NULL;
  273. ts->pids[pid] = filter;
  274. filter->type = MPEGTS_SECTION;
  275. filter->pid = pid;
  276. filter->es_id = -1;
  277. filter->last_cc = -1;
  278. sec = &filter->u.section_filter;
  279. sec->section_cb = section_cb;
  280. sec->opaque = opaque;
  281. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  282. sec->check_crc = check_crc;
  283. if (!sec->section_buf) {
  284. av_free(filter);
  285. return NULL;
  286. }
  287. return filter;
  288. }
  289. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  290. PESCallback *pes_cb,
  291. void *opaque)
  292. {
  293. MpegTSFilter *filter;
  294. MpegTSPESFilter *pes;
  295. if (pid >= NB_PID_MAX || ts->pids[pid])
  296. return NULL;
  297. filter = av_mallocz(sizeof(MpegTSFilter));
  298. if (!filter)
  299. return NULL;
  300. ts->pids[pid] = filter;
  301. filter->type = MPEGTS_PES;
  302. filter->pid = pid;
  303. filter->es_id = -1;
  304. filter->last_cc = -1;
  305. pes = &filter->u.pes_filter;
  306. pes->pes_cb = pes_cb;
  307. pes->opaque = opaque;
  308. return filter;
  309. }
  310. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  311. {
  312. int pid;
  313. pid = filter->pid;
  314. if (filter->type == MPEGTS_SECTION)
  315. av_freep(&filter->u.section_filter.section_buf);
  316. else if (filter->type == MPEGTS_PES) {
  317. PESContext *pes = filter->u.pes_filter.opaque;
  318. av_freep(&pes->buffer);
  319. /* referenced private data will be freed later in
  320. * avformat_close_input */
  321. if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  322. av_freep(&filter->u.pes_filter.opaque);
  323. }
  324. }
  325. av_free(filter);
  326. ts->pids[pid] = NULL;
  327. }
  328. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  329. int stat[TS_MAX_PACKET_SIZE];
  330. int i;
  331. int x=0;
  332. int best_score=0;
  333. memset(stat, 0, packet_size*sizeof(int));
  334. for(x=i=0; i<size-3; i++){
  335. if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
  336. stat[x]++;
  337. if(stat[x] > best_score){
  338. best_score= stat[x];
  339. if(index) *index= x;
  340. }
  341. }
  342. x++;
  343. if(x == packet_size) x= 0;
  344. }
  345. return best_score;
  346. }
  347. /* autodetect fec presence. Must have at least 1024 bytes */
  348. static int get_packet_size(const uint8_t *buf, int size)
  349. {
  350. int score, fec_score, dvhs_score;
  351. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  352. return -1;
  353. score = analyze(buf, size, TS_PACKET_SIZE, NULL);
  354. dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  355. fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  356. av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  357. 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 AVCodecID codec_id;
  445. } StreamType;
  446. static const StreamType ISO_types[] = {
  447. { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  448. { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
  449. { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  450. { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
  451. { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
  452. { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
  453. { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
  454. { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
  455. { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  456. { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  457. { 0 },
  458. };
  459. static const StreamType HDMV_types[] = {
  460. { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
  461. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  462. { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  463. { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
  464. { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  465. { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
  466. { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
  467. { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
  468. { 0 },
  469. };
  470. /* ATSC ? */
  471. static const StreamType MISC_types[] = {
  472. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  473. { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  474. { 0 },
  475. };
  476. static const StreamType REGD_types[] = {
  477. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  478. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  479. { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
  480. { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  481. { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  482. { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  483. { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  484. { 0 },
  485. };
  486. /* descriptor present */
  487. static const StreamType DESC_types[] = {
  488. { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
  489. { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  490. { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  491. { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
  492. { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  493. { 0 },
  494. };
  495. static void mpegts_find_stream_type(AVStream *st,
  496. uint32_t stream_type, const StreamType *types)
  497. {
  498. for (; types->stream_type; types++) {
  499. if (stream_type == types->stream_type) {
  500. st->codec->codec_type = types->codec_type;
  501. st->codec->codec_id = types->codec_id;
  502. return;
  503. }
  504. }
  505. }
  506. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  507. uint32_t stream_type, uint32_t prog_reg_desc)
  508. {
  509. avpriv_set_pts_info(st, 33, 1, 90000);
  510. st->priv_data = pes;
  511. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  512. st->codec->codec_id = AV_CODEC_ID_NONE;
  513. st->need_parsing = AVSTREAM_PARSE_FULL;
  514. pes->st = st;
  515. pes->stream_type = stream_type;
  516. av_log(pes->stream, AV_LOG_DEBUG,
  517. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  518. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  519. st->codec->codec_tag = pes->stream_type;
  520. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  521. if (prog_reg_desc == AV_RL32("HDMV") &&
  522. st->codec->codec_id == AV_CODEC_ID_NONE) {
  523. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  524. if (pes->stream_type == 0x83) {
  525. // HDMV TrueHD streams also contain an AC3 coded version of the
  526. // audio track - add a second stream for this
  527. AVStream *sub_st;
  528. // priv_data cannot be shared between streams
  529. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  530. if (!sub_pes)
  531. return AVERROR(ENOMEM);
  532. memcpy(sub_pes, pes, sizeof(*sub_pes));
  533. sub_st = avformat_new_stream(pes->stream, NULL);
  534. if (!sub_st) {
  535. av_free(sub_pes);
  536. return AVERROR(ENOMEM);
  537. }
  538. sub_st->id = pes->pid;
  539. avpriv_set_pts_info(sub_st, 33, 1, 90000);
  540. sub_st->priv_data = sub_pes;
  541. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  542. sub_st->codec->codec_id = AV_CODEC_ID_AC3;
  543. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  544. sub_pes->sub_st = pes->sub_st = sub_st;
  545. }
  546. }
  547. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  548. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  549. return 0;
  550. }
  551. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  552. {
  553. av_init_packet(pkt);
  554. pkt->destruct = av_destruct_packet;
  555. pkt->data = pes->buffer;
  556. pkt->size = pes->data_index;
  557. if(pes->total_size != MAX_PES_PAYLOAD &&
  558. pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
  559. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  560. pes->flags |= AV_PKT_FLAG_CORRUPT;
  561. }
  562. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  563. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  564. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  565. pkt->stream_index = pes->sub_st->index;
  566. else
  567. pkt->stream_index = pes->st->index;
  568. pkt->pts = pes->pts;
  569. pkt->dts = pes->dts;
  570. /* store position of first TS packet of this PES packet */
  571. pkt->pos = pes->ts_packet_pos;
  572. pkt->flags = pes->flags;
  573. /* reset pts values */
  574. pes->pts = AV_NOPTS_VALUE;
  575. pes->dts = AV_NOPTS_VALUE;
  576. pes->buffer = NULL;
  577. pes->data_index = 0;
  578. pes->flags = 0;
  579. }
  580. static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
  581. {
  582. GetBitContext gb;
  583. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  584. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  585. int dts_flag = -1, cts_flag = -1;
  586. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  587. init_get_bits(&gb, buf, buf_size*8);
  588. if (sl->use_au_start)
  589. au_start_flag = get_bits1(&gb);
  590. if (sl->use_au_end)
  591. au_end_flag = get_bits1(&gb);
  592. if (!sl->use_au_start && !sl->use_au_end)
  593. au_start_flag = au_end_flag = 1;
  594. if (sl->ocr_len > 0)
  595. ocr_flag = get_bits1(&gb);
  596. if (sl->use_idle)
  597. idle_flag = get_bits1(&gb);
  598. if (sl->use_padding)
  599. padding_flag = get_bits1(&gb);
  600. if (padding_flag)
  601. padding_bits = get_bits(&gb, 3);
  602. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  603. if (sl->packet_seq_num_len)
  604. skip_bits_long(&gb, sl->packet_seq_num_len);
  605. if (sl->degr_prior_len)
  606. if (get_bits1(&gb))
  607. skip_bits(&gb, sl->degr_prior_len);
  608. if (ocr_flag)
  609. skip_bits_long(&gb, sl->ocr_len);
  610. if (au_start_flag) {
  611. if (sl->use_rand_acc_pt)
  612. get_bits1(&gb);
  613. if (sl->au_seq_num_len > 0)
  614. skip_bits_long(&gb, sl->au_seq_num_len);
  615. if (sl->use_timestamps) {
  616. dts_flag = get_bits1(&gb);
  617. cts_flag = get_bits1(&gb);
  618. }
  619. }
  620. if (sl->inst_bitrate_len)
  621. inst_bitrate_flag = get_bits1(&gb);
  622. if (dts_flag == 1)
  623. dts = get_bits64(&gb, sl->timestamp_len);
  624. if (cts_flag == 1)
  625. cts = get_bits64(&gb, sl->timestamp_len);
  626. if (sl->au_len > 0)
  627. skip_bits_long(&gb, sl->au_len);
  628. if (inst_bitrate_flag)
  629. skip_bits_long(&gb, sl->inst_bitrate_len);
  630. }
  631. if (dts != AV_NOPTS_VALUE)
  632. pes->dts = dts;
  633. if (cts != AV_NOPTS_VALUE)
  634. pes->pts = cts;
  635. if (sl->timestamp_len && sl->timestamp_res)
  636. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  637. return (get_bits_count(&gb) + 7) >> 3;
  638. }
  639. /* return non zero if a packet could be constructed */
  640. static int mpegts_push_data(MpegTSFilter *filter,
  641. const uint8_t *buf, int buf_size, int is_start,
  642. int64_t pos)
  643. {
  644. PESContext *pes = filter->u.pes_filter.opaque;
  645. MpegTSContext *ts = pes->ts;
  646. const uint8_t *p;
  647. int len, code;
  648. if(!ts->pkt)
  649. return 0;
  650. if (is_start) {
  651. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  652. new_pes_packet(pes, ts->pkt);
  653. ts->stop_parse = 1;
  654. }
  655. pes->state = MPEGTS_HEADER;
  656. pes->data_index = 0;
  657. pes->ts_packet_pos = pos;
  658. }
  659. p = buf;
  660. while (buf_size > 0) {
  661. switch(pes->state) {
  662. case MPEGTS_HEADER:
  663. len = PES_START_SIZE - pes->data_index;
  664. if (len > buf_size)
  665. len = buf_size;
  666. memcpy(pes->header + pes->data_index, p, len);
  667. pes->data_index += len;
  668. p += len;
  669. buf_size -= len;
  670. if (pes->data_index == PES_START_SIZE) {
  671. /* we got all the PES or section header. We can now
  672. decide */
  673. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  674. pes->header[2] == 0x01) {
  675. /* it must be an mpeg2 PES stream */
  676. code = pes->header[3] | 0x100;
  677. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  678. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  679. (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
  680. code == 0x1be) /* padding_stream */
  681. goto skip;
  682. /* stream not present in PMT */
  683. if (!pes->st) {
  684. pes->st = avformat_new_stream(ts->stream, NULL);
  685. if (!pes->st)
  686. return AVERROR(ENOMEM);
  687. pes->st->id = pes->pid;
  688. mpegts_set_stream_info(pes->st, pes, 0, 0);
  689. }
  690. pes->total_size = AV_RB16(pes->header + 4);
  691. /* NOTE: a zero total size means the PES size is
  692. unbounded */
  693. if (!pes->total_size)
  694. pes->total_size = MAX_PES_PAYLOAD;
  695. /* allocate pes buffer */
  696. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  697. if (!pes->buffer)
  698. return AVERROR(ENOMEM);
  699. if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
  700. code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
  701. code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
  702. code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
  703. pes->state = MPEGTS_PESHEADER;
  704. if (pes->st->codec->codec_id == AV_CODEC_ID_NONE) {
  705. av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
  706. pes->pid, pes->stream_type);
  707. pes->st->codec->codec_id = AV_CODEC_ID_PROBE;
  708. }
  709. } else {
  710. pes->state = MPEGTS_PAYLOAD;
  711. pes->data_index = 0;
  712. }
  713. } else {
  714. /* otherwise, it should be a table */
  715. /* skip packet */
  716. skip:
  717. pes->state = MPEGTS_SKIP;
  718. continue;
  719. }
  720. }
  721. break;
  722. /**********************************************/
  723. /* PES packing parsing */
  724. case MPEGTS_PESHEADER:
  725. len = PES_HEADER_SIZE - pes->data_index;
  726. if (len < 0)
  727. return -1;
  728. if (len > buf_size)
  729. len = buf_size;
  730. memcpy(pes->header + pes->data_index, p, len);
  731. pes->data_index += len;
  732. p += len;
  733. buf_size -= len;
  734. if (pes->data_index == PES_HEADER_SIZE) {
  735. pes->pes_header_size = pes->header[8] + 9;
  736. pes->state = MPEGTS_PESHEADER_FILL;
  737. }
  738. break;
  739. case MPEGTS_PESHEADER_FILL:
  740. len = pes->pes_header_size - pes->data_index;
  741. if (len < 0)
  742. return -1;
  743. if (len > buf_size)
  744. len = buf_size;
  745. memcpy(pes->header + pes->data_index, p, len);
  746. pes->data_index += len;
  747. p += len;
  748. buf_size -= len;
  749. if (pes->data_index == pes->pes_header_size) {
  750. const uint8_t *r;
  751. unsigned int flags, pes_ext, skip;
  752. flags = pes->header[7];
  753. r = pes->header + 9;
  754. pes->pts = AV_NOPTS_VALUE;
  755. pes->dts = AV_NOPTS_VALUE;
  756. if ((flags & 0xc0) == 0x80) {
  757. pes->dts = pes->pts = ff_parse_pes_pts(r);
  758. r += 5;
  759. } else if ((flags & 0xc0) == 0xc0) {
  760. pes->pts = ff_parse_pes_pts(r);
  761. r += 5;
  762. pes->dts = ff_parse_pes_pts(r);
  763. r += 5;
  764. }
  765. pes->extended_stream_id = -1;
  766. if (flags & 0x01) { /* PES extension */
  767. pes_ext = *r++;
  768. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  769. skip = (pes_ext >> 4) & 0xb;
  770. skip += skip & 0x9;
  771. r += skip;
  772. if ((pes_ext & 0x41) == 0x01 &&
  773. (r + 2) <= (pes->header + pes->pes_header_size)) {
  774. /* PES extension 2 */
  775. if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
  776. pes->extended_stream_id = r[1];
  777. }
  778. }
  779. /* we got the full header. We parse it and get the payload */
  780. pes->state = MPEGTS_PAYLOAD;
  781. pes->data_index = 0;
  782. if (pes->stream_type == 0x12 && buf_size > 0) {
  783. int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
  784. pes->pes_header_size += sl_header_bytes;
  785. p += sl_header_bytes;
  786. buf_size -= sl_header_bytes;
  787. }
  788. }
  789. break;
  790. case MPEGTS_PAYLOAD:
  791. if (buf_size > 0 && pes->buffer) {
  792. if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
  793. new_pes_packet(pes, ts->pkt);
  794. pes->total_size = MAX_PES_PAYLOAD;
  795. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  796. if (!pes->buffer)
  797. return AVERROR(ENOMEM);
  798. ts->stop_parse = 1;
  799. } else if (pes->data_index == 0 && buf_size > pes->total_size) {
  800. // pes packet size is < ts size packet and pes data is padded with 0xff
  801. // not sure if this is legal in ts but see issue #2392
  802. buf_size = pes->total_size;
  803. }
  804. memcpy(pes->buffer+pes->data_index, p, buf_size);
  805. pes->data_index += buf_size;
  806. }
  807. buf_size = 0;
  808. /* emit complete packets with known packet size
  809. * decreases demuxer delay for infrequent packets like subtitles from
  810. * a couple of seconds to milliseconds for properly muxed files.
  811. * total_size is the number of bytes following pes_packet_length
  812. * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
  813. if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
  814. pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
  815. ts->stop_parse = 1;
  816. new_pes_packet(pes, ts->pkt);
  817. }
  818. break;
  819. case MPEGTS_SKIP:
  820. buf_size = 0;
  821. break;
  822. }
  823. }
  824. return 0;
  825. }
  826. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
  827. {
  828. MpegTSFilter *tss;
  829. PESContext *pes;
  830. /* if no pid found, then add a pid context */
  831. pes = av_mallocz(sizeof(PESContext));
  832. if (!pes)
  833. return 0;
  834. pes->ts = ts;
  835. pes->stream = ts->stream;
  836. pes->pid = pid;
  837. pes->pcr_pid = pcr_pid;
  838. pes->state = MPEGTS_SKIP;
  839. pes->pts = AV_NOPTS_VALUE;
  840. pes->dts = AV_NOPTS_VALUE;
  841. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  842. if (!tss) {
  843. av_free(pes);
  844. return 0;
  845. }
  846. return pes;
  847. }
  848. #define MAX_LEVEL 4
  849. typedef struct {
  850. AVFormatContext *s;
  851. AVIOContext pb;
  852. Mp4Descr *descr;
  853. Mp4Descr *active_descr;
  854. int descr_count;
  855. int max_descr_count;
  856. int level;
  857. } MP4DescrParseContext;
  858. static int init_MP4DescrParseContext(
  859. MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
  860. unsigned size, Mp4Descr *descr, int max_descr_count)
  861. {
  862. int ret;
  863. if (size > (1<<30))
  864. return AVERROR_INVALIDDATA;
  865. if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
  866. NULL, NULL, NULL, NULL)) < 0)
  867. return ret;
  868. d->s = s;
  869. d->level = 0;
  870. d->descr_count = 0;
  871. d->descr = descr;
  872. d->active_descr = NULL;
  873. d->max_descr_count = max_descr_count;
  874. return 0;
  875. }
  876. static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
  877. int64_t new_off = avio_tell(pb);
  878. (*len) -= new_off - *off;
  879. *off = new_off;
  880. }
  881. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  882. int target_tag);
  883. static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
  884. {
  885. while (len > 0) {
  886. if (parse_mp4_descr(d, off, len, 0) < 0)
  887. return -1;
  888. update_offsets(&d->pb, &off, &len);
  889. }
  890. return 0;
  891. }
  892. static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  893. {
  894. avio_rb16(&d->pb); // ID
  895. avio_r8(&d->pb);
  896. avio_r8(&d->pb);
  897. avio_r8(&d->pb);
  898. avio_r8(&d->pb);
  899. avio_r8(&d->pb);
  900. update_offsets(&d->pb, &off, &len);
  901. return parse_mp4_descr_arr(d, off, len);
  902. }
  903. static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
  904. {
  905. int id_flags;
  906. if (len < 2)
  907. return 0;
  908. id_flags = avio_rb16(&d->pb);
  909. if (!(id_flags & 0x0020)) { //URL_Flag
  910. update_offsets(&d->pb, &off, &len);
  911. return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
  912. } else {
  913. return 0;
  914. }
  915. }
  916. static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  917. {
  918. int es_id = 0;
  919. if (d->descr_count >= d->max_descr_count)
  920. return -1;
  921. ff_mp4_parse_es_descr(&d->pb, &es_id);
  922. d->active_descr = d->descr + (d->descr_count++);
  923. d->active_descr->es_id = es_id;
  924. update_offsets(&d->pb, &off, &len);
  925. parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
  926. update_offsets(&d->pb, &off, &len);
  927. if (len > 0)
  928. parse_mp4_descr(d, off, len, MP4SLDescrTag);
  929. d->active_descr = NULL;
  930. return 0;
  931. }
  932. static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  933. {
  934. Mp4Descr *descr = d->active_descr;
  935. if (!descr)
  936. return -1;
  937. d->active_descr->dec_config_descr = av_malloc(len);
  938. if (!descr->dec_config_descr)
  939. return AVERROR(ENOMEM);
  940. descr->dec_config_descr_len = len;
  941. avio_read(&d->pb, descr->dec_config_descr, len);
  942. return 0;
  943. }
  944. static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
  945. {
  946. Mp4Descr *descr = d->active_descr;
  947. int predefined;
  948. if (!descr)
  949. return -1;
  950. predefined = avio_r8(&d->pb);
  951. if (!predefined) {
  952. int lengths;
  953. int flags = avio_r8(&d->pb);
  954. descr->sl.use_au_start = !!(flags & 0x80);
  955. descr->sl.use_au_end = !!(flags & 0x40);
  956. descr->sl.use_rand_acc_pt = !!(flags & 0x20);
  957. descr->sl.use_padding = !!(flags & 0x08);
  958. descr->sl.use_timestamps = !!(flags & 0x04);
  959. descr->sl.use_idle = !!(flags & 0x02);
  960. descr->sl.timestamp_res = avio_rb32(&d->pb);
  961. avio_rb32(&d->pb);
  962. descr->sl.timestamp_len = avio_r8(&d->pb);
  963. descr->sl.ocr_len = avio_r8(&d->pb);
  964. descr->sl.au_len = avio_r8(&d->pb);
  965. descr->sl.inst_bitrate_len = avio_r8(&d->pb);
  966. lengths = avio_rb16(&d->pb);
  967. descr->sl.degr_prior_len = lengths >> 12;
  968. descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
  969. descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
  970. } else {
  971. av_log_missing_feature(d->s, "Predefined SLConfigDescriptor\n", 0);
  972. }
  973. return 0;
  974. }
  975. static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
  976. int target_tag) {
  977. int tag;
  978. int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
  979. update_offsets(&d->pb, &off, &len);
  980. if (len < 0 || len1 > len || len1 <= 0) {
  981. av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
  982. return -1;
  983. }
  984. if (d->level++ >= MAX_LEVEL) {
  985. av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
  986. goto done;
  987. }
  988. if (target_tag && tag != target_tag) {
  989. av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
  990. goto done;
  991. }
  992. switch (tag) {
  993. case MP4IODescrTag:
  994. parse_MP4IODescrTag(d, off, len1);
  995. break;
  996. case MP4ODescrTag:
  997. parse_MP4ODescrTag(d, off, len1);
  998. break;
  999. case MP4ESDescrTag:
  1000. parse_MP4ESDescrTag(d, off, len1);
  1001. break;
  1002. case MP4DecConfigDescrTag:
  1003. parse_MP4DecConfigDescrTag(d, off, len1);
  1004. break;
  1005. case MP4SLDescrTag:
  1006. parse_MP4SLDescrTag(d, off, len1);
  1007. break;
  1008. }
  1009. done:
  1010. d->level--;
  1011. avio_seek(&d->pb, off + len1, SEEK_SET);
  1012. return 0;
  1013. }
  1014. static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1015. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1016. {
  1017. MP4DescrParseContext d;
  1018. if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1019. return -1;
  1020. parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
  1021. *descr_count = d.descr_count;
  1022. return 0;
  1023. }
  1024. static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
  1025. Mp4Descr *descr, int *descr_count, int max_descr_count)
  1026. {
  1027. MP4DescrParseContext d;
  1028. if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
  1029. return -1;
  1030. parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
  1031. *descr_count = d.descr_count;
  1032. return 0;
  1033. }
  1034. static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1035. {
  1036. MpegTSContext *ts = filter->u.section_filter.opaque;
  1037. SectionHeader h;
  1038. const uint8_t *p, *p_end;
  1039. AVIOContext pb;
  1040. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1041. int mp4_descr_count = 0;
  1042. int i, pid;
  1043. AVFormatContext *s = ts->stream;
  1044. p_end = section + section_len - 4;
  1045. p = section;
  1046. if (parse_section_header(&h, &p, p_end) < 0)
  1047. return;
  1048. if (h.tid != M4OD_TID)
  1049. return;
  1050. mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1051. for (pid = 0; pid < NB_PID_MAX; pid++) {
  1052. if (!ts->pids[pid])
  1053. continue;
  1054. for (i = 0; i < mp4_descr_count; i++) {
  1055. PESContext *pes;
  1056. AVStream *st;
  1057. if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
  1058. continue;
  1059. if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
  1060. av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
  1061. continue;
  1062. }
  1063. pes = ts->pids[pid]->u.pes_filter.opaque;
  1064. st = pes->st;
  1065. if (!st) {
  1066. continue;
  1067. }
  1068. pes->sl = mp4_descr[i].sl;
  1069. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1070. mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1071. ff_mp4_read_dec_config_descr(s, st, &pb);
  1072. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1073. st->codec->extradata_size > 0)
  1074. st->need_parsing = 0;
  1075. if (st->codec->codec_id == AV_CODEC_ID_H264 &&
  1076. st->codec->extradata_size > 0)
  1077. st->need_parsing = 0;
  1078. if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
  1079. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
  1080. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1081. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
  1082. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1083. } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
  1084. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1085. }
  1086. }
  1087. }
  1088. for (i = 0; i < mp4_descr_count; i++)
  1089. av_free(mp4_descr[i].dec_config_descr);
  1090. }
  1091. int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
  1092. const uint8_t **pp, const uint8_t *desc_list_end,
  1093. Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
  1094. MpegTSContext *ts)
  1095. {
  1096. const uint8_t *desc_end;
  1097. int desc_len, desc_tag, desc_es_id;
  1098. char language[252];
  1099. int i;
  1100. desc_tag = get8(pp, desc_list_end);
  1101. if (desc_tag < 0)
  1102. return -1;
  1103. desc_len = get8(pp, desc_list_end);
  1104. if (desc_len < 0)
  1105. return -1;
  1106. desc_end = *pp + desc_len;
  1107. if (desc_end > desc_list_end)
  1108. return -1;
  1109. av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
  1110. if (st->codec->codec_id == AV_CODEC_ID_NONE &&
  1111. stream_type == STREAM_TYPE_PRIVATE_DATA)
  1112. mpegts_find_stream_type(st, desc_tag, DESC_types);
  1113. switch(desc_tag) {
  1114. case 0x1E: /* SL descriptor */
  1115. desc_es_id = get16(pp, desc_end);
  1116. if (ts && ts->pids[pid])
  1117. ts->pids[pid]->es_id = desc_es_id;
  1118. for (i = 0; i < mp4_descr_count; i++)
  1119. if (mp4_descr[i].dec_config_descr_len &&
  1120. mp4_descr[i].es_id == desc_es_id) {
  1121. AVIOContext pb;
  1122. ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
  1123. mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1124. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1125. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1126. st->codec->extradata_size > 0)
  1127. st->need_parsing = 0;
  1128. if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
  1129. mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
  1130. }
  1131. break;
  1132. case 0x1F: /* FMC descriptor */
  1133. get16(pp, desc_end);
  1134. if (mp4_descr_count > 0 && st->codec->codec_id == AV_CODEC_ID_AAC_LATM &&
  1135. mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
  1136. AVIOContext pb;
  1137. ffio_init_context(&pb, mp4_descr->dec_config_descr,
  1138. mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
  1139. ff_mp4_read_dec_config_descr(fc, st, &pb);
  1140. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  1141. st->codec->extradata_size > 0)
  1142. st->need_parsing = 0;
  1143. }
  1144. break;
  1145. case 0x56: /* DVB teletext descriptor */
  1146. language[0] = get8(pp, desc_end);
  1147. language[1] = get8(pp, desc_end);
  1148. language[2] = get8(pp, desc_end);
  1149. language[3] = 0;
  1150. av_dict_set(&st->metadata, "language", language, 0);
  1151. break;
  1152. case 0x59: /* subtitling descriptor */
  1153. language[0] = get8(pp, desc_end);
  1154. language[1] = get8(pp, desc_end);
  1155. language[2] = get8(pp, desc_end);
  1156. language[3] = 0;
  1157. /* hearing impaired subtitles detection */
  1158. switch(get8(pp, desc_end)) {
  1159. case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
  1160. case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
  1161. case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
  1162. case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
  1163. case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
  1164. case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
  1165. st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  1166. break;
  1167. }
  1168. if (st->codec->extradata) {
  1169. if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
  1170. av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
  1171. } else {
  1172. st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
  1173. if (st->codec->extradata) {
  1174. st->codec->extradata_size = 4;
  1175. memcpy(st->codec->extradata, *pp, 4);
  1176. }
  1177. }
  1178. *pp += 4;
  1179. av_dict_set(&st->metadata, "language", language, 0);
  1180. break;
  1181. case 0x0a: /* ISO 639 language descriptor */
  1182. for (i = 0; i + 4 <= desc_len; i += 4) {
  1183. language[i + 0] = get8(pp, desc_end);
  1184. language[i + 1] = get8(pp, desc_end);
  1185. language[i + 2] = get8(pp, desc_end);
  1186. language[i + 3] = ',';
  1187. switch (get8(pp, desc_end)) {
  1188. case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
  1189. case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
  1190. case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
  1191. }
  1192. }
  1193. if (i) {
  1194. language[i - 1] = 0;
  1195. av_dict_set(&st->metadata, "language", language, 0);
  1196. }
  1197. break;
  1198. case 0x05: /* registration descriptor */
  1199. st->codec->codec_tag = bytestream_get_le32(pp);
  1200. av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
  1201. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1202. mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
  1203. break;
  1204. default:
  1205. break;
  1206. }
  1207. *pp = desc_end;
  1208. return 0;
  1209. }
  1210. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1211. {
  1212. MpegTSContext *ts = filter->u.section_filter.opaque;
  1213. SectionHeader h1, *h = &h1;
  1214. PESContext *pes;
  1215. AVStream *st;
  1216. const uint8_t *p, *p_end, *desc_list_end;
  1217. int program_info_length, pcr_pid, pid, stream_type;
  1218. int desc_list_len;
  1219. uint32_t prog_reg_desc = 0; /* registration descriptor */
  1220. Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
  1221. int mp4_descr_count = 0;
  1222. int i;
  1223. av_dlog(ts->stream, "PMT: len %i\n", section_len);
  1224. hex_dump_debug(ts->stream, section, section_len);
  1225. p_end = section + section_len - 4;
  1226. p = section;
  1227. if (parse_section_header(h, &p, p_end) < 0)
  1228. return;
  1229. av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  1230. h->id, h->sec_num, h->last_sec_num);
  1231. if (h->tid != PMT_TID)
  1232. return;
  1233. clear_program(ts, h->id);
  1234. pcr_pid = get16(&p, p_end);
  1235. if (pcr_pid < 0)
  1236. return;
  1237. pcr_pid &= 0x1fff;
  1238. add_pid_to_pmt(ts, h->id, pcr_pid);
  1239. av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  1240. program_info_length = get16(&p, p_end);
  1241. if (program_info_length < 0)
  1242. return;
  1243. program_info_length &= 0xfff;
  1244. while(program_info_length >= 2) {
  1245. uint8_t tag, len;
  1246. tag = get8(&p, p_end);
  1247. len = get8(&p, p_end);
  1248. av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
  1249. if(len > program_info_length - 2)
  1250. //something else is broken, exit the program_descriptors_loop
  1251. break;
  1252. program_info_length -= len + 2;
  1253. if (tag == 0x1d) { // IOD descriptor
  1254. get8(&p, p_end); // scope
  1255. get8(&p, p_end); // label
  1256. len -= 2;
  1257. mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
  1258. &mp4_descr_count, MAX_MP4_DESCR_COUNT);
  1259. } else if (tag == 0x05 && len >= 4) { // registration descriptor
  1260. prog_reg_desc = bytestream_get_le32(&p);
  1261. len -= 4;
  1262. }
  1263. p += len;
  1264. }
  1265. p += program_info_length;
  1266. if (p >= p_end)
  1267. goto out;
  1268. // stop parsing after pmt, we found header
  1269. if (!ts->stream->nb_streams)
  1270. ts->stop_parse = 1;
  1271. for(;;) {
  1272. st = 0;
  1273. pes = NULL;
  1274. stream_type = get8(&p, p_end);
  1275. if (stream_type < 0)
  1276. break;
  1277. pid = get16(&p, p_end);
  1278. if (pid < 0)
  1279. break;
  1280. pid &= 0x1fff;
  1281. /* now create stream */
  1282. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  1283. pes = ts->pids[pid]->u.pes_filter.opaque;
  1284. if (!pes->st) {
  1285. pes->st = avformat_new_stream(pes->stream, NULL);
  1286. pes->st->id = pes->pid;
  1287. }
  1288. st = pes->st;
  1289. } else if (stream_type != 0x13) {
  1290. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  1291. pes = add_pes_stream(ts, pid, pcr_pid);
  1292. if (pes) {
  1293. st = avformat_new_stream(pes->stream, NULL);
  1294. st->id = pes->pid;
  1295. }
  1296. } else {
  1297. int idx = ff_find_stream_index(ts->stream, pid);
  1298. if (idx >= 0) {
  1299. st = ts->stream->streams[idx];
  1300. } else {
  1301. st = avformat_new_stream(ts->stream, NULL);
  1302. st->id = pid;
  1303. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1304. }
  1305. }
  1306. if (!st)
  1307. goto out;
  1308. if (pes && !pes->stream_type)
  1309. mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
  1310. add_pid_to_pmt(ts, h->id, pid);
  1311. ff_program_add_stream_index(ts->stream, h->id, st->index);
  1312. desc_list_len = get16(&p, p_end);
  1313. if (desc_list_len < 0)
  1314. break;
  1315. desc_list_len &= 0xfff;
  1316. desc_list_end = p + desc_list_len;
  1317. if (desc_list_end > p_end)
  1318. break;
  1319. for(;;) {
  1320. if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
  1321. mp4_descr, mp4_descr_count, pid, ts) < 0)
  1322. break;
  1323. if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
  1324. ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
  1325. pes->sub_st->codec->codec_tag = st->codec->codec_tag;
  1326. }
  1327. }
  1328. p = desc_list_end;
  1329. }
  1330. out:
  1331. for (i = 0; i < mp4_descr_count; i++)
  1332. av_free(mp4_descr[i].dec_config_descr);
  1333. }
  1334. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1335. {
  1336. MpegTSContext *ts = filter->u.section_filter.opaque;
  1337. SectionHeader h1, *h = &h1;
  1338. const uint8_t *p, *p_end;
  1339. int sid, pmt_pid;
  1340. av_dlog(ts->stream, "PAT:\n");
  1341. hex_dump_debug(ts->stream, section, section_len);
  1342. p_end = section + section_len - 4;
  1343. p = section;
  1344. if (parse_section_header(h, &p, p_end) < 0)
  1345. return;
  1346. if (h->tid != PAT_TID)
  1347. return;
  1348. clear_programs(ts);
  1349. for(;;) {
  1350. sid = get16(&p, p_end);
  1351. if (sid < 0)
  1352. break;
  1353. pmt_pid = get16(&p, p_end);
  1354. if (pmt_pid < 0)
  1355. break;
  1356. pmt_pid &= 0x1fff;
  1357. av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  1358. if (sid == 0x0000) {
  1359. /* NIT info */
  1360. } else {
  1361. av_new_program(ts->stream, sid);
  1362. if (ts->pids[pmt_pid])
  1363. mpegts_close_filter(ts, ts->pids[pmt_pid]);
  1364. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  1365. add_pat_entry(ts, sid);
  1366. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  1367. add_pid_to_pmt(ts, sid, pmt_pid);
  1368. }
  1369. }
  1370. }
  1371. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1372. {
  1373. MpegTSContext *ts = filter->u.section_filter.opaque;
  1374. SectionHeader h1, *h = &h1;
  1375. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1376. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1377. char *name, *provider_name;
  1378. av_dlog(ts->stream, "SDT:\n");
  1379. hex_dump_debug(ts->stream, section, section_len);
  1380. p_end = section + section_len - 4;
  1381. p = section;
  1382. if (parse_section_header(h, &p, p_end) < 0)
  1383. return;
  1384. if (h->tid != SDT_TID)
  1385. return;
  1386. onid = get16(&p, p_end);
  1387. if (onid < 0)
  1388. return;
  1389. val = get8(&p, p_end);
  1390. if (val < 0)
  1391. return;
  1392. for(;;) {
  1393. sid = get16(&p, p_end);
  1394. if (sid < 0)
  1395. break;
  1396. val = get8(&p, p_end);
  1397. if (val < 0)
  1398. break;
  1399. desc_list_len = get16(&p, p_end);
  1400. if (desc_list_len < 0)
  1401. break;
  1402. desc_list_len &= 0xfff;
  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+FF_INPUT_BUFFER_PADDING_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. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  1604. for(;;) {
  1605. if (ts->stop_parse>0)
  1606. break;
  1607. packet_num++;
  1608. if (nb_packets != 0 && packet_num >= nb_packets)
  1609. break;
  1610. ret = read_packet(s, packet, ts->raw_packet_size);
  1611. if (ret != 0)
  1612. break;
  1613. ret = handle_packet(ts, packet);
  1614. if (ret != 0)
  1615. break;
  1616. }
  1617. ts->last_pos = avio_tell(s->pb);
  1618. return ret;
  1619. }
  1620. static int mpegts_probe(AVProbeData *p)
  1621. {
  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_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
  1632. score, dvhs_score, fec_score);
  1633. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1634. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1635. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1636. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1637. else return -1;
  1638. }
  1639. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1640. (-1) if not available */
  1641. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1642. const uint8_t *packet)
  1643. {
  1644. int afc, len, flags;
  1645. const uint8_t *p;
  1646. unsigned int v;
  1647. afc = (packet[3] >> 4) & 3;
  1648. if (afc <= 1)
  1649. return -1;
  1650. p = packet + 4;
  1651. len = p[0];
  1652. p++;
  1653. if (len == 0)
  1654. return -1;
  1655. flags = *p++;
  1656. len--;
  1657. if (!(flags & 0x10))
  1658. return -1;
  1659. if (len < 6)
  1660. return -1;
  1661. v = AV_RB32(p);
  1662. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1663. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1664. return 0;
  1665. }
  1666. static int mpegts_read_header(AVFormatContext *s)
  1667. {
  1668. MpegTSContext *ts = s->priv_data;
  1669. AVIOContext *pb = s->pb;
  1670. uint8_t buf[5*1024];
  1671. int len;
  1672. int64_t pos;
  1673. /* read the first 1024 bytes to get packet size */
  1674. pos = avio_tell(pb);
  1675. len = avio_read(pb, buf, sizeof(buf));
  1676. if (len != sizeof(buf))
  1677. goto fail;
  1678. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1679. if (ts->raw_packet_size <= 0)
  1680. goto fail;
  1681. ts->stream = s;
  1682. ts->auto_guess = 0;
  1683. if (s->iformat == &ff_mpegts_demuxer) {
  1684. /* normal demux */
  1685. /* first do a scan to get all the services */
  1686. if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
  1687. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1688. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1689. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1690. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1691. /* if could not find service, enable auto_guess */
  1692. ts->auto_guess = 1;
  1693. av_dlog(ts->stream, "tuning done\n");
  1694. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1695. } else {
  1696. AVStream *st;
  1697. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1698. int64_t pcrs[2], pcr_h;
  1699. int packet_count[2];
  1700. uint8_t packet[TS_PACKET_SIZE];
  1701. /* only read packets */
  1702. st = avformat_new_stream(s, NULL);
  1703. if (!st)
  1704. goto fail;
  1705. avpriv_set_pts_info(st, 60, 1, 27000000);
  1706. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1707. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  1708. /* we iterate until we find two PCRs to estimate the bitrate */
  1709. pcr_pid = -1;
  1710. nb_pcrs = 0;
  1711. nb_packets = 0;
  1712. for(;;) {
  1713. ret = read_packet(s, packet, ts->raw_packet_size);
  1714. if (ret < 0)
  1715. return -1;
  1716. pid = AV_RB16(packet + 1) & 0x1fff;
  1717. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1718. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1719. pcr_pid = pid;
  1720. packet_count[nb_pcrs] = nb_packets;
  1721. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1722. nb_pcrs++;
  1723. if (nb_pcrs >= 2)
  1724. break;
  1725. }
  1726. nb_packets++;
  1727. }
  1728. /* NOTE1: the bitrate is computed without the FEC */
  1729. /* NOTE2: it is only the bitrate of the start of the stream */
  1730. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1731. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1732. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1733. st->codec->bit_rate = s->bit_rate;
  1734. st->start_time = ts->cur_pcr;
  1735. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  1736. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1737. }
  1738. avio_seek(pb, pos, SEEK_SET);
  1739. return 0;
  1740. fail:
  1741. return -1;
  1742. }
  1743. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1744. static int mpegts_raw_read_packet(AVFormatContext *s,
  1745. AVPacket *pkt)
  1746. {
  1747. MpegTSContext *ts = s->priv_data;
  1748. int ret, i;
  1749. int64_t pcr_h, next_pcr_h, pos;
  1750. int pcr_l, next_pcr_l;
  1751. uint8_t pcr_buf[12];
  1752. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1753. return AVERROR(ENOMEM);
  1754. pkt->pos= avio_tell(s->pb);
  1755. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1756. if (ret < 0) {
  1757. av_free_packet(pkt);
  1758. return ret;
  1759. }
  1760. if (ts->mpeg2ts_compute_pcr) {
  1761. /* compute exact PCR for each packet */
  1762. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1763. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1764. pos = avio_tell(s->pb);
  1765. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1766. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1767. avio_read(s->pb, pcr_buf, 12);
  1768. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1769. /* XXX: not precise enough */
  1770. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1771. (i + 1);
  1772. break;
  1773. }
  1774. }
  1775. avio_seek(s->pb, pos, SEEK_SET);
  1776. /* no next PCR found: we use previous increment */
  1777. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1778. }
  1779. pkt->pts = ts->cur_pcr;
  1780. pkt->duration = ts->pcr_incr;
  1781. ts->cur_pcr += ts->pcr_incr;
  1782. }
  1783. pkt->stream_index = 0;
  1784. return 0;
  1785. }
  1786. static int mpegts_read_packet(AVFormatContext *s,
  1787. AVPacket *pkt)
  1788. {
  1789. MpegTSContext *ts = s->priv_data;
  1790. int ret, i;
  1791. pkt->size = -1;
  1792. ts->pkt = pkt;
  1793. ret = handle_packets(ts, 0);
  1794. if (ret < 0) {
  1795. /* flush pes data left */
  1796. for (i = 0; i < NB_PID_MAX; i++) {
  1797. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1798. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1799. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1800. new_pes_packet(pes, pkt);
  1801. pes->state = MPEGTS_SKIP;
  1802. ret = 0;
  1803. break;
  1804. }
  1805. }
  1806. }
  1807. }
  1808. if (!ret && pkt->size < 0)
  1809. ret = AVERROR(EINTR);
  1810. return ret;
  1811. }
  1812. static int mpegts_read_close(AVFormatContext *s)
  1813. {
  1814. MpegTSContext *ts = s->priv_data;
  1815. int i;
  1816. clear_programs(ts);
  1817. for(i=0;i<NB_PID_MAX;i++)
  1818. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1819. return 0;
  1820. }
  1821. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1822. int64_t *ppos, int64_t pos_limit)
  1823. {
  1824. MpegTSContext *ts = s->priv_data;
  1825. int64_t pos, timestamp;
  1826. uint8_t buf[TS_PACKET_SIZE];
  1827. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1828. const int find_next= 1;
  1829. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1830. if (find_next) {
  1831. for(;;) {
  1832. avio_seek(s->pb, pos, SEEK_SET);
  1833. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1834. return AV_NOPTS_VALUE;
  1835. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1836. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1837. break;
  1838. }
  1839. pos += ts->raw_packet_size;
  1840. }
  1841. } else {
  1842. for(;;) {
  1843. pos -= ts->raw_packet_size;
  1844. if (pos < 0)
  1845. return AV_NOPTS_VALUE;
  1846. avio_seek(s->pb, pos, SEEK_SET);
  1847. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1848. return AV_NOPTS_VALUE;
  1849. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1850. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1851. break;
  1852. }
  1853. }
  1854. }
  1855. *ppos = pos;
  1856. return timestamp;
  1857. }
  1858. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1859. MpegTSContext *ts = s->priv_data;
  1860. uint8_t buf[TS_PACKET_SIZE];
  1861. int64_t pos;
  1862. if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1863. return -1;
  1864. pos= avio_tell(s->pb);
  1865. for(;;) {
  1866. avio_seek(s->pb, pos, SEEK_SET);
  1867. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1868. return -1;
  1869. // pid = AV_RB16(buf + 1) & 0x1fff;
  1870. if(buf[1] & 0x40) break;
  1871. pos += ts->raw_packet_size;
  1872. }
  1873. avio_seek(s->pb, pos, SEEK_SET);
  1874. return 0;
  1875. }
  1876. /**************************************************************/
  1877. /* parsing functions - called from other demuxers such as RTP */
  1878. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1879. {
  1880. MpegTSContext *ts;
  1881. ts = av_mallocz(sizeof(MpegTSContext));
  1882. if (!ts)
  1883. return NULL;
  1884. /* no stream case, currently used by RTP */
  1885. ts->raw_packet_size = TS_PACKET_SIZE;
  1886. ts->stream = s;
  1887. ts->auto_guess = 1;
  1888. return ts;
  1889. }
  1890. /* return the consumed length if a packet was output, or -1 if no
  1891. packet is output */
  1892. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1893. const uint8_t *buf, int len)
  1894. {
  1895. int len1;
  1896. len1 = len;
  1897. ts->pkt = pkt;
  1898. ts->stop_parse = 0;
  1899. for(;;) {
  1900. if (ts->stop_parse>0)
  1901. break;
  1902. if (len < TS_PACKET_SIZE)
  1903. return -1;
  1904. if (buf[0] != 0x47) {
  1905. buf++;
  1906. len--;
  1907. } else {
  1908. handle_packet(ts, buf);
  1909. buf += TS_PACKET_SIZE;
  1910. len -= TS_PACKET_SIZE;
  1911. }
  1912. }
  1913. return len1 - len;
  1914. }
  1915. void ff_mpegts_parse_close(MpegTSContext *ts)
  1916. {
  1917. int i;
  1918. for(i=0;i<NB_PID_MAX;i++)
  1919. av_free(ts->pids[i]);
  1920. av_free(ts);
  1921. }
  1922. AVInputFormat ff_mpegts_demuxer = {
  1923. .name = "mpegts",
  1924. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  1925. .priv_data_size = sizeof(MpegTSContext),
  1926. .read_probe = mpegts_probe,
  1927. .read_header = mpegts_read_header,
  1928. .read_packet = mpegts_read_packet,
  1929. .read_close = mpegts_read_close,
  1930. .read_seek = read_seek,
  1931. .read_timestamp = mpegts_get_pcr,
  1932. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  1933. };
  1934. AVInputFormat ff_mpegtsraw_demuxer = {
  1935. .name = "mpegtsraw",
  1936. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  1937. .priv_data_size = sizeof(MpegTSContext),
  1938. .read_header = mpegts_read_header,
  1939. .read_packet = mpegts_raw_read_packet,
  1940. .read_close = mpegts_read_close,
  1941. .read_seek = read_seek,
  1942. .read_timestamp = mpegts_get_pcr,
  1943. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  1944. .priv_class = &mpegtsraw_class,
  1945. };