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.

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