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.

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