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.

2299 lines
72KB

  1. /*
  2. * MPEG2 transport stream (aka DVB) demuxer
  3. * Copyright (c) 2002-2003 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. //#define USE_SYNCPOINT_SEARCH
  22. #include "libavutil/crc.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/log.h"
  25. #include "libavutil/dict.h"
  26. #include "libavutil/mathematics.h"
  27. #include "libavutil/opt.h"
  28. #include "libavcodec/bytestream.h"
  29. #include "libavcodec/get_bits.h"
  30. #include "avformat.h"
  31. #include "mpegts.h"
  32. #include "internal.h"
  33. #include "avio_internal.h"
  34. #include "seek.h"
  35. #include "mpeg.h"
  36. #include "isom.h"
  37. /* maximum size in which we look for synchronisation if
  38. synchronisation is lost */
  39. #define MAX_RESYNC_SIZE 65536
  40. #define MAX_PES_PAYLOAD 200*1024
  41. #define MAX_MP4_DESCR_COUNT 16
  42. enum MpegTSFilterType {
  43. MPEGTS_PES,
  44. MPEGTS_SECTION,
  45. };
  46. typedef struct MpegTSFilter MpegTSFilter;
  47. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
  48. typedef struct MpegTSPESFilter {
  49. PESCallback *pes_cb;
  50. void *opaque;
  51. } MpegTSPESFilter;
  52. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  53. typedef void SetServiceCallback(void *opaque, int ret);
  54. typedef struct MpegTSSectionFilter {
  55. int section_index;
  56. int section_h_size;
  57. uint8_t *section_buf;
  58. unsigned int check_crc:1;
  59. unsigned int end_of_section_reached:1;
  60. SectionCallback *section_cb;
  61. void *opaque;
  62. } MpegTSSectionFilter;
  63. struct MpegTSFilter {
  64. int pid;
  65. int es_id;
  66. int last_cc; /* last cc code (-1 if first packet) */
  67. enum MpegTSFilterType type;
  68. union {
  69. MpegTSPESFilter pes_filter;
  70. MpegTSSectionFilter section_filter;
  71. } u;
  72. };
  73. #define MAX_PIDS_PER_PROGRAM 64
  74. struct Program {
  75. unsigned int id; //program id/service id
  76. unsigned int nb_pids;
  77. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  78. };
  79. struct MpegTSContext {
  80. const AVClass *class;
  81. /* user data */
  82. AVFormatContext *stream;
  83. /** raw packet size, including FEC if present */
  84. int raw_packet_size;
  85. int pos47;
  86. /** if true, all pids are analyzed to find streams */
  87. int auto_guess;
  88. /** compute exact PCR for each transport stream packet */
  89. int mpeg2ts_compute_pcr;
  90. int64_t cur_pcr; /**< used to estimate the exact PCR */
  91. int pcr_incr; /**< used to estimate the exact PCR */
  92. /* data needed to handle file based ts */
  93. /** stop parsing loop */
  94. int stop_parse;
  95. /** packet containing Audio/Video data */
  96. AVPacket *pkt;
  97. /** to detect seek */
  98. int64_t last_pos;
  99. /******************************************/
  100. /* private mpegts data */
  101. /* scan context */
  102. /** structure to keep track of Program->pids mapping */
  103. unsigned int nb_prg;
  104. struct Program *prg;
  105. /** filters for various streams specified by PMT + for the PAT and PMT */
  106. MpegTSFilter *pids[NB_PID_MAX];
  107. };
  108. static const AVOption options[] = {
  109. {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
  110. {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  111. { NULL },
  112. };
  113. static const AVClass mpegtsraw_class = {
  114. .class_name = "mpegtsraw demuxer",
  115. .item_name = av_default_item_name,
  116. .option = options,
  117. .version = LIBAVUTIL_VERSION_INT,
  118. };
  119. /* TS stream handling */
  120. enum MpegTSState {
  121. MPEGTS_HEADER = 0,
  122. MPEGTS_PESHEADER,
  123. MPEGTS_PESHEADER_FILL,
  124. MPEGTS_PAYLOAD,
  125. MPEGTS_SKIP,
  126. };
  127. /* enough for PES header + length */
  128. #define PES_START_SIZE 6
  129. #define PES_HEADER_SIZE 9
  130. #define MAX_PES_HEADER_SIZE (9 + 255)
  131. typedef struct PESContext {
  132. int pid;
  133. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  134. int stream_type;
  135. MpegTSContext *ts;
  136. AVFormatContext *stream;
  137. AVStream *st;
  138. AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
  139. enum MpegTSState state;
  140. /* used to get the format */
  141. int data_index;
  142. int flags; /**< copied to the AVPacket flags */
  143. int total_size;
  144. int pes_header_size;
  145. int extended_stream_id;
  146. int64_t pts, dts;
  147. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  148. uint8_t header[MAX_PES_HEADER_SIZE];
  149. uint8_t *buffer;
  150. SLConfigDescr sl;
  151. } PESContext;
  152. extern AVInputFormat ff_mpegts_demuxer;
  153. static void clear_program(MpegTSContext *ts, unsigned int programid)
  154. {
  155. int i;
  156. for(i=0; i<ts->nb_prg; i++)
  157. if(ts->prg[i].id == programid)
  158. ts->prg[i].nb_pids = 0;
  159. }
  160. static void clear_programs(MpegTSContext *ts)
  161. {
  162. av_freep(&ts->prg);
  163. ts->nb_prg=0;
  164. }
  165. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  166. {
  167. struct Program *p;
  168. void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
  169. if(!tmp)
  170. return;
  171. ts->prg = tmp;
  172. p = &ts->prg[ts->nb_prg];
  173. p->id = programid;
  174. p->nb_pids = 0;
  175. ts->nb_prg++;
  176. }
  177. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  178. {
  179. int i;
  180. struct Program *p = NULL;
  181. for(i=0; i<ts->nb_prg; i++) {
  182. if(ts->prg[i].id == programid) {
  183. p = &ts->prg[i];
  184. break;
  185. }
  186. }
  187. if(!p)
  188. return;
  189. if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  190. return;
  191. p->pids[p->nb_pids++] = pid;
  192. }
  193. /**
  194. * @brief discard_pid() decides if the pid is to be discarded according
  195. * to caller's programs selection
  196. * @param ts : - TS context
  197. * @param pid : - pid
  198. * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  199. * 0 otherwise
  200. */
  201. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  202. {
  203. int i, j, k;
  204. int used = 0, discarded = 0;
  205. struct Program *p;
  206. for(i=0; i<ts->nb_prg; i++) {
  207. p = &ts->prg[i];
  208. for(j=0; j<p->nb_pids; j++) {
  209. if(p->pids[j] != pid)
  210. continue;
  211. //is program with id p->id set to be discarded?
  212. for(k=0; k<ts->stream->nb_programs; k++) {
  213. if(ts->stream->programs[k]->id == p->id) {
  214. if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  215. discarded++;
  216. else
  217. used++;
  218. }
  219. }
  220. }
  221. }
  222. return !used && discarded;
  223. }
  224. /**
  225. * Assemble PES packets out of TS packets, and then call the "section_cb"
  226. * function when they are complete.
  227. */
  228. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  229. const uint8_t *buf, int buf_size, int is_start)
  230. {
  231. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  232. int len;
  233. if (is_start) {
  234. memcpy(tss->section_buf, buf, buf_size);
  235. tss->section_index = buf_size;
  236. tss->section_h_size = -1;
  237. tss->end_of_section_reached = 0;
  238. } else {
  239. if (tss->end_of_section_reached)
  240. return;
  241. len = 4096 - tss->section_index;
  242. if (buf_size < len)
  243. len = buf_size;
  244. memcpy(tss->section_buf + tss->section_index, buf, len);
  245. tss->section_index += len;
  246. }
  247. /* compute section length if possible */
  248. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  249. len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  250. if (len > 4096)
  251. return;
  252. tss->section_h_size = len;
  253. }
  254. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  255. tss->end_of_section_reached = 1;
  256. if (!tss->check_crc ||
  257. av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
  258. tss->section_buf, tss->section_h_size) == 0)
  259. tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  260. }
  261. }
  262. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  263. SectionCallback *section_cb, void *opaque,
  264. int check_crc)
  265. {
  266. MpegTSFilter *filter;
  267. MpegTSSectionFilter *sec;
  268. av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
  269. if (pid >= NB_PID_MAX || ts->pids[pid])
  270. return NULL;
  271. filter = av_mallocz(sizeof(MpegTSFilter));
  272. if (!filter)
  273. return NULL;
  274. ts->pids[pid] = filter;
  275. filter->type = MPEGTS_SECTION;
  276. filter->pid = pid;
  277. filter->es_id = -1;
  278. filter->last_cc = -1;
  279. sec = &filter->u.section_filter;
  280. sec->section_cb = section_cb;
  281. sec->opaque = opaque;
  282. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  283. sec->check_crc = check_crc;
  284. if (!sec->section_buf) {
  285. av_free(filter);
  286. return NULL;
  287. }
  288. return filter;
  289. }
  290. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  291. PESCallback *pes_cb,
  292. void *opaque)
  293. {
  294. MpegTSFilter *filter;
  295. MpegTSPESFilter *pes;
  296. if (pid >= NB_PID_MAX || ts->pids[pid])
  297. return NULL;
  298. filter = av_mallocz(sizeof(MpegTSFilter));
  299. if (!filter)
  300. return NULL;
  301. ts->pids[pid] = filter;
  302. filter->type = MPEGTS_PES;
  303. filter->pid = pid;
  304. filter->es_id = -1;
  305. filter->last_cc = -1;
  306. pes = &filter->u.pes_filter;
  307. pes->pes_cb = pes_cb;
  308. pes->opaque = opaque;
  309. return filter;
  310. }
  311. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  312. {
  313. int pid;
  314. pid = filter->pid;
  315. if (filter->type == MPEGTS_SECTION)
  316. av_freep(&filter->u.section_filter.section_buf);
  317. else if (filter->type == MPEGTS_PES) {
  318. PESContext *pes = filter->u.pes_filter.opaque;
  319. av_freep(&pes->buffer);
  320. /* referenced private data will be freed later in
  321. * avformat_close_input */
  322. if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  323. av_freep(&filter->u.pes_filter.opaque);
  324. }
  325. }
  326. av_free(filter);
  327. ts->pids[pid] = NULL;
  328. }
  329. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  330. int stat[TS_MAX_PACKET_SIZE];
  331. int i;
  332. int x=0;
  333. int best_score=0;
  334. memset(stat, 0, packet_size*sizeof(int));
  335. for(x=i=0; i<size-3; i++){
  336. if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
  337. stat[x]++;
  338. if(stat[x] > best_score){
  339. best_score= stat[x];
  340. if(index) *index= x;
  341. }
  342. }
  343. x++;
  344. if(x == packet_size) x= 0;
  345. }
  346. return best_score;
  347. }
  348. /* autodetect fec presence. Must have at least 1024 bytes */
  349. static int get_packet_size(const uint8_t *buf, int size)
  350. {
  351. int score, fec_score, dvhs_score;
  352. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  353. return -1;
  354. score = analyze(buf, size, TS_PACKET_SIZE, NULL);
  355. dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  356. fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  357. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  358. if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  359. else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  360. else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  361. else return -1;
  362. }
  363. typedef struct SectionHeader {
  364. uint8_t tid;
  365. uint16_t id;
  366. uint8_t version;
  367. uint8_t sec_num;
  368. uint8_t last_sec_num;
  369. } SectionHeader;
  370. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  371. {
  372. const uint8_t *p;
  373. int c;
  374. p = *pp;
  375. if (p >= p_end)
  376. return -1;
  377. c = *p++;
  378. *pp = p;
  379. return c;
  380. }
  381. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  382. {
  383. const uint8_t *p;
  384. int c;
  385. p = *pp;
  386. if ((p + 1) >= p_end)
  387. return -1;
  388. c = AV_RB16(p);
  389. p += 2;
  390. *pp = p;
  391. return c;
  392. }
  393. /* read and allocate a DVB string preceded by its length */
  394. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  395. {
  396. int len;
  397. const uint8_t *p;
  398. char *str;
  399. p = *pp;
  400. len = get8(&p, p_end);
  401. if (len < 0)
  402. return NULL;
  403. if ((p + len) > p_end)
  404. return NULL;
  405. str = av_malloc(len + 1);
  406. if (!str)
  407. return NULL;
  408. memcpy(str, p, len);
  409. str[len] = '\0';
  410. p += len;
  411. *pp = p;
  412. return str;
  413. }
  414. static int parse_section_header(SectionHeader *h,
  415. const uint8_t **pp, const uint8_t *p_end)
  416. {
  417. int val;
  418. val = get8(pp, p_end);
  419. if (val < 0)
  420. return -1;
  421. h->tid = val;
  422. *pp += 2;
  423. val = get16(pp, p_end);
  424. if (val < 0)
  425. return -1;
  426. h->id = val;
  427. val = get8(pp, p_end);
  428. if (val < 0)
  429. return -1;
  430. h->version = (val >> 1) & 0x1f;
  431. val = get8(pp, p_end);
  432. if (val < 0)
  433. return -1;
  434. h->sec_num = val;
  435. val = get8(pp, p_end);
  436. if (val < 0)
  437. return -1;
  438. h->last_sec_num = val;
  439. return 0;
  440. }
  441. typedef struct {
  442. uint32_t stream_type;
  443. enum AVMediaType codec_type;
  444. enum CodecID codec_id;
  445. } StreamType;
  446. static const StreamType ISO_types[] = {
  447. { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  448. { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  449. { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
  450. { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
  451. { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
  452. { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
  453. { 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC_LATM }, /* LATM syntax */
  454. { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
  455. { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
  456. { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
  457. { 0 },
  458. };
  459. static const StreamType HDMV_types[] = {
  460. { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
  461. { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  462. { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  463. { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
  464. { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
  465. { 0x85, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS }, /* DTS HD */
  466. { 0x86, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS }, /* DTS HD MASTER*/
  467. { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
  468. { 0 },
  469. };
  470. /* ATSC ? */
  471. static const StreamType MISC_types[] = {
  472. { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  473. { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  474. { 0 },
  475. };
  476. static const StreamType REGD_types[] = {
  477. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
  478. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
  479. { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, CODEC_ID_S302M },
  480. { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  481. { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  482. { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  483. { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
  484. { 0 },
  485. };
  486. /* descriptor present */
  487. static const StreamType DESC_types[] = {
  488. { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
  489. { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  490. { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
  491. { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
  492. { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  493. { 0 },
  494. };
  495. static void mpegts_find_stream_type(AVStream *st,
  496. uint32_t stream_type, const StreamType *types)
  497. {
  498. for (; types->stream_type; types++) {
  499. if (stream_type == types->stream_type) {
  500. st->codec->codec_type = types->codec_type;
  501. st->codec->codec_id = types->codec_id;
  502. return;
  503. }
  504. }
  505. }
  506. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  507. uint32_t stream_type, uint32_t prog_reg_desc)
  508. {
  509. avpriv_set_pts_info(st, 33, 1, 90000);
  510. st->priv_data = pes;
  511. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  512. st->codec->codec_id = CODEC_ID_NONE;
  513. st->need_parsing = AVSTREAM_PARSE_FULL;
  514. pes->st = st;
  515. pes->stream_type = stream_type;
  516. av_log(pes->stream, AV_LOG_DEBUG,
  517. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  518. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  519. st->codec->codec_tag = pes->stream_type;
  520. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  521. if (prog_reg_desc == AV_RL32("HDMV") &&
  522. st->codec->codec_id == CODEC_ID_NONE) {
  523. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  524. if (pes->stream_type == 0x83) {
  525. // HDMV TrueHD streams also contain an AC3 coded version of the
  526. // audio track - add a second stream for this
  527. AVStream *sub_st;
  528. // priv_data cannot be shared between streams
  529. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  530. if (!sub_pes)
  531. return AVERROR(ENOMEM);
  532. memcpy(sub_pes, pes, sizeof(*sub_pes));
  533. sub_st = avformat_new_stream(pes->stream, NULL);
  534. if (!sub_st) {
  535. av_free(sub_pes);
  536. return AVERROR(ENOMEM);
  537. }
  538. sub_st->id = pes->pid;
  539. avpriv_set_pts_info(sub_st, 33, 1, 90000);
  540. sub_st->priv_data = sub_pes;
  541. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  542. sub_st->codec->codec_id = CODEC_ID_AC3;
  543. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  544. sub_pes->sub_st = pes->sub_st = sub_st;
  545. }
  546. }
  547. if (st->codec->codec_id == CODEC_ID_NONE)
  548. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  549. return 0;
  550. }
  551. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  552. {
  553. av_init_packet(pkt);
  554. pkt->destruct = av_destruct_packet;
  555. pkt->data = pes->buffer;
  556. pkt->size = pes->data_index;
  557. if(pes->total_size != MAX_PES_PAYLOAD &&
  558. pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
  559. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  560. pes->flags |= AV_PKT_FLAG_CORRUPT;
  561. }
  562. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  563. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  564. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  565. pkt->stream_index = pes->sub_st->index;
  566. else
  567. pkt->stream_index = pes->st->index;
  568. pkt->pts = pes->pts;
  569. pkt->dts = pes->dts;
  570. /* store position of first TS packet of this PES packet */
  571. pkt->pos = pes->ts_packet_pos;
  572. pkt->flags = pes->flags;
  573. /* reset pts values */
  574. pes->pts = AV_NOPTS_VALUE;
  575. pes->dts = AV_NOPTS_VALUE;
  576. pes->buffer = NULL;
  577. pes->data_index = 0;
  578. pes->flags = 0;
  579. }
  580. static uint64_t get_bits64(GetBitContext *gb, int bits)
  581. {
  582. uint64_t ret = 0;
  583. while (bits > 17) {
  584. ret <<= 17;
  585. ret |= get_bits(gb, 17);
  586. bits -= 17;
  587. }
  588. ret <<= bits;
  589. ret |= get_bits(gb, bits);
  590. return ret;
  591. }
  592. static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
  593. {
  594. GetBitContext gb;
  595. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  596. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  597. int dts_flag = -1, cts_flag = -1;
  598. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  599. init_get_bits(&gb, buf, buf_size*8);
  600. if (sl->use_au_start)
  601. au_start_flag = get_bits1(&gb);
  602. if (sl->use_au_end)
  603. au_end_flag = get_bits1(&gb);
  604. if (!sl->use_au_start && !sl->use_au_end)
  605. au_start_flag = au_end_flag = 1;
  606. if (sl->ocr_len > 0)
  607. ocr_flag = get_bits1(&gb);
  608. if (sl->use_idle)
  609. idle_flag = get_bits1(&gb);
  610. if (sl->use_padding)
  611. padding_flag = get_bits1(&gb);
  612. if (padding_flag)
  613. padding_bits = get_bits(&gb, 3);
  614. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  615. if (sl->packet_seq_num_len)
  616. skip_bits_long(&gb, sl->packet_seq_num_len);
  617. if (sl->degr_prior_len)
  618. if (get_bits1(&gb))
  619. skip_bits(&gb, sl->degr_prior_len);
  620. if (ocr_flag)
  621. skip_bits_long(&gb, sl->ocr_len);
  622. if (au_start_flag) {
  623. if (sl->use_rand_acc_pt)
  624. get_bits1(&gb);
  625. if (sl->au_seq_num_len > 0)
  626. skip_bits_long(&gb, sl->au_seq_num_len);
  627. if (sl->use_timestamps) {
  628. dts_flag = get_bits1(&gb);
  629. cts_flag = get_bits1(&gb);
  630. }
  631. }
  632. if (sl->inst_bitrate_len)
  633. inst_bitrate_flag = get_bits1(&gb);
  634. if (dts_flag == 1)
  635. dts = get_bits64(&gb, sl->timestamp_len);
  636. if (cts_flag == 1)
  637. cts = get_bits64(&gb, sl->timestamp_len);
  638. if (sl->au_len > 0)
  639. skip_bits_long(&gb, sl->au_len);
  640. if (inst_bitrate_flag)
  641. skip_bits_long(&gb, sl->inst_bitrate_len);
  642. }
  643. if (dts != AV_NOPTS_VALUE)
  644. pes->dts = dts;
  645. if (cts != AV_NOPTS_VALUE)
  646. pes->pts = cts;
  647. if (sl->timestamp_len && sl->timestamp_res)
  648. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  649. return (get_bits_count(&gb) + 7) >> 3;
  650. }
  651. /* return non zero if a packet could be constructed */
  652. static int mpegts_push_data(MpegTSFilter *filter,
  653. const uint8_t *buf, int buf_size, int is_start,
  654. int64_t pos)
  655. {
  656. PESContext *pes = filter->u.pes_filter.opaque;
  657. MpegTSContext *ts = pes->ts;
  658. const uint8_t *p;
  659. int len, code;
  660. if(!ts->pkt)
  661. return 0;
  662. if (is_start) {
  663. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  664. new_pes_packet(pes, ts->pkt);
  665. ts->stop_parse = 1;
  666. }
  667. pes->state = MPEGTS_HEADER;
  668. pes->data_index = 0;
  669. pes->ts_packet_pos = pos;
  670. }
  671. p = buf;
  672. while (buf_size > 0) {
  673. switch(pes->state) {
  674. case MPEGTS_HEADER:
  675. len = PES_START_SIZE - pes->data_index;
  676. if (len > buf_size)
  677. len = buf_size;
  678. memcpy(pes->header + pes->data_index, p, len);
  679. pes->data_index += len;
  680. p += len;
  681. buf_size -= len;
  682. if (pes->data_index == PES_START_SIZE) {
  683. /* we got all the PES or section header. We can now
  684. decide */
  685. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  686. pes->header[2] == 0x01) {
  687. /* it must be an mpeg2 PES stream */
  688. code = pes->header[3] | 0x100;
  689. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  690. if ((pes->st && pes->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 == 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 = 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 == CODEC_ID_AAC &&
  1084. st->codec->extradata_size > 0)
  1085. st->need_parsing = 0;
  1086. if (st->codec->codec_id == CODEC_ID_H264 &&
  1087. st->codec->extradata_size > 0)
  1088. st->need_parsing = 0;
  1089. if (st->codec->codec_id <= CODEC_ID_NONE) {
  1090. } else if (st->codec->codec_id < CODEC_ID_FIRST_AUDIO) {
  1091. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1092. } else if (st->codec->codec_id < CODEC_ID_FIRST_SUBTITLE) {
  1093. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1094. } else if (st->codec->codec_id < 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 == 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 == CODEC_ID_AAC &&
  1137. st->codec->extradata_size > 0)
  1138. st->need_parsing = 0;
  1139. if (st->codec->codec_id == 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 == 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 == 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 == 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. #if 1
  1634. const int size= p->buf_size;
  1635. int score, fec_score, dvhs_score;
  1636. int check_count= size / TS_FEC_PACKET_SIZE;
  1637. #define CHECK_COUNT 10
  1638. if (check_count < CHECK_COUNT)
  1639. return -1;
  1640. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1641. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1642. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1643. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1644. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1645. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1646. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1647. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1648. else return -1;
  1649. #else
  1650. /* only use the extension for safer guess */
  1651. if (av_match_ext(p->filename, "ts"))
  1652. return AVPROBE_SCORE_MAX;
  1653. else
  1654. return 0;
  1655. #endif
  1656. }
  1657. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1658. (-1) if not available */
  1659. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1660. const uint8_t *packet)
  1661. {
  1662. int afc, len, flags;
  1663. const uint8_t *p;
  1664. unsigned int v;
  1665. afc = (packet[3] >> 4) & 3;
  1666. if (afc <= 1)
  1667. return -1;
  1668. p = packet + 4;
  1669. len = p[0];
  1670. p++;
  1671. if (len == 0)
  1672. return -1;
  1673. flags = *p++;
  1674. len--;
  1675. if (!(flags & 0x10))
  1676. return -1;
  1677. if (len < 6)
  1678. return -1;
  1679. v = AV_RB32(p);
  1680. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1681. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1682. return 0;
  1683. }
  1684. static int mpegts_read_header(AVFormatContext *s)
  1685. {
  1686. MpegTSContext *ts = s->priv_data;
  1687. AVIOContext *pb = s->pb;
  1688. uint8_t buf[5*1024];
  1689. int len;
  1690. int64_t pos;
  1691. /* read the first 1024 bytes to get packet size */
  1692. pos = avio_tell(pb);
  1693. len = avio_read(pb, buf, sizeof(buf));
  1694. if (len != sizeof(buf))
  1695. goto fail;
  1696. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1697. if (ts->raw_packet_size <= 0)
  1698. goto fail;
  1699. ts->stream = s;
  1700. ts->auto_guess = 0;
  1701. if (s->iformat == &ff_mpegts_demuxer) {
  1702. /* normal demux */
  1703. /* first do a scan to get all the services */
  1704. if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
  1705. av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
  1706. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1707. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1708. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1709. /* if could not find service, enable auto_guess */
  1710. ts->auto_guess = 1;
  1711. av_dlog(ts->stream, "tuning done\n");
  1712. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1713. } else {
  1714. AVStream *st;
  1715. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1716. int64_t pcrs[2], pcr_h;
  1717. int packet_count[2];
  1718. uint8_t packet[TS_PACKET_SIZE];
  1719. /* only read packets */
  1720. st = avformat_new_stream(s, NULL);
  1721. if (!st)
  1722. goto fail;
  1723. avpriv_set_pts_info(st, 60, 1, 27000000);
  1724. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1725. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1726. /* we iterate until we find two PCRs to estimate the bitrate */
  1727. pcr_pid = -1;
  1728. nb_pcrs = 0;
  1729. nb_packets = 0;
  1730. for(;;) {
  1731. ret = read_packet(s, packet, ts->raw_packet_size);
  1732. if (ret < 0)
  1733. return -1;
  1734. pid = AV_RB16(packet + 1) & 0x1fff;
  1735. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1736. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1737. pcr_pid = pid;
  1738. packet_count[nb_pcrs] = nb_packets;
  1739. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1740. nb_pcrs++;
  1741. if (nb_pcrs >= 2)
  1742. break;
  1743. }
  1744. nb_packets++;
  1745. }
  1746. /* NOTE1: the bitrate is computed without the FEC */
  1747. /* NOTE2: it is only the bitrate of the start of the stream */
  1748. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1749. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1750. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1751. st->codec->bit_rate = s->bit_rate;
  1752. st->start_time = ts->cur_pcr;
  1753. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  1754. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1755. }
  1756. avio_seek(pb, pos, SEEK_SET);
  1757. return 0;
  1758. fail:
  1759. return -1;
  1760. }
  1761. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1762. static int mpegts_raw_read_packet(AVFormatContext *s,
  1763. AVPacket *pkt)
  1764. {
  1765. MpegTSContext *ts = s->priv_data;
  1766. int ret, i;
  1767. int64_t pcr_h, next_pcr_h, pos;
  1768. int pcr_l, next_pcr_l;
  1769. uint8_t pcr_buf[12];
  1770. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1771. return AVERROR(ENOMEM);
  1772. pkt->pos= avio_tell(s->pb);
  1773. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1774. if (ret < 0) {
  1775. av_free_packet(pkt);
  1776. return ret;
  1777. }
  1778. if (ts->mpeg2ts_compute_pcr) {
  1779. /* compute exact PCR for each packet */
  1780. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1781. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1782. pos = avio_tell(s->pb);
  1783. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1784. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1785. avio_read(s->pb, pcr_buf, 12);
  1786. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1787. /* XXX: not precise enough */
  1788. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1789. (i + 1);
  1790. break;
  1791. }
  1792. }
  1793. avio_seek(s->pb, pos, SEEK_SET);
  1794. /* no next PCR found: we use previous increment */
  1795. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1796. }
  1797. pkt->pts = ts->cur_pcr;
  1798. pkt->duration = ts->pcr_incr;
  1799. ts->cur_pcr += ts->pcr_incr;
  1800. }
  1801. pkt->stream_index = 0;
  1802. return 0;
  1803. }
  1804. static int mpegts_read_packet(AVFormatContext *s,
  1805. AVPacket *pkt)
  1806. {
  1807. MpegTSContext *ts = s->priv_data;
  1808. int ret, i;
  1809. pkt->size = -1;
  1810. ts->pkt = pkt;
  1811. ret = handle_packets(ts, 0);
  1812. if (ret < 0) {
  1813. /* flush pes data left */
  1814. for (i = 0; i < NB_PID_MAX; i++) {
  1815. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1816. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1817. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1818. new_pes_packet(pes, pkt);
  1819. pes->state = MPEGTS_SKIP;
  1820. ret = 0;
  1821. break;
  1822. }
  1823. }
  1824. }
  1825. }
  1826. if (!ret && pkt->size < 0)
  1827. ret = AVERROR(EINTR);
  1828. return ret;
  1829. }
  1830. static int mpegts_read_close(AVFormatContext *s)
  1831. {
  1832. MpegTSContext *ts = s->priv_data;
  1833. int i;
  1834. clear_programs(ts);
  1835. for(i=0;i<NB_PID_MAX;i++)
  1836. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1837. return 0;
  1838. }
  1839. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1840. int64_t *ppos, int64_t pos_limit)
  1841. {
  1842. MpegTSContext *ts = s->priv_data;
  1843. int64_t pos, timestamp;
  1844. uint8_t buf[TS_PACKET_SIZE];
  1845. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1846. const int find_next= 1;
  1847. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1848. if (find_next) {
  1849. for(;;) {
  1850. avio_seek(s->pb, pos, SEEK_SET);
  1851. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1852. return AV_NOPTS_VALUE;
  1853. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1854. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1855. break;
  1856. }
  1857. pos += ts->raw_packet_size;
  1858. }
  1859. } else {
  1860. for(;;) {
  1861. pos -= ts->raw_packet_size;
  1862. if (pos < 0)
  1863. return AV_NOPTS_VALUE;
  1864. avio_seek(s->pb, pos, SEEK_SET);
  1865. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1866. return AV_NOPTS_VALUE;
  1867. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1868. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1869. break;
  1870. }
  1871. }
  1872. }
  1873. *ppos = pos;
  1874. return timestamp;
  1875. }
  1876. #ifdef USE_SYNCPOINT_SEARCH
  1877. static int read_seek2(AVFormatContext *s,
  1878. int stream_index,
  1879. int64_t min_ts,
  1880. int64_t target_ts,
  1881. int64_t max_ts,
  1882. int flags)
  1883. {
  1884. int64_t pos;
  1885. int64_t ts_ret, ts_adj;
  1886. int stream_index_gen_search;
  1887. AVStream *st;
  1888. AVParserState *backup;
  1889. backup = ff_store_parser_state(s);
  1890. // detect direction of seeking for search purposes
  1891. flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
  1892. AVSEEK_FLAG_BACKWARD : 0;
  1893. if (flags & AVSEEK_FLAG_BYTE) {
  1894. // use position directly, we will search starting from it
  1895. pos = target_ts;
  1896. } else {
  1897. // search for some position with good timestamp match
  1898. if (stream_index < 0) {
  1899. stream_index_gen_search = av_find_default_stream_index(s);
  1900. if (stream_index_gen_search < 0) {
  1901. ff_restore_parser_state(s, backup);
  1902. return -1;
  1903. }
  1904. st = s->streams[stream_index_gen_search];
  1905. // timestamp for default must be expressed in AV_TIME_BASE units
  1906. ts_adj = av_rescale(target_ts,
  1907. st->time_base.den,
  1908. AV_TIME_BASE * (int64_t)st->time_base.num);
  1909. } else {
  1910. ts_adj = target_ts;
  1911. stream_index_gen_search = stream_index;
  1912. }
  1913. pos = ff_gen_search(s, stream_index_gen_search, ts_adj,
  1914. 0, INT64_MAX, -1,
  1915. AV_NOPTS_VALUE,
  1916. AV_NOPTS_VALUE,
  1917. flags, &ts_ret, mpegts_get_pcr);
  1918. if (pos < 0) {
  1919. ff_restore_parser_state(s, backup);
  1920. return -1;
  1921. }
  1922. }
  1923. // search for actual matching keyframe/starting position for all streams
  1924. if (ff_gen_syncpoint_search(s, stream_index, pos,
  1925. min_ts, target_ts, max_ts,
  1926. flags) < 0) {
  1927. ff_restore_parser_state(s, backup);
  1928. return -1;
  1929. }
  1930. ff_free_parser_state(s, backup);
  1931. return 0;
  1932. }
  1933. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
  1934. {
  1935. int ret;
  1936. if (flags & AVSEEK_FLAG_BACKWARD) {
  1937. flags &= ~AVSEEK_FLAG_BACKWARD;
  1938. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
  1939. if (ret < 0)
  1940. // for compatibility reasons, seek to the best-fitting timestamp
  1941. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1942. } else {
  1943. ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
  1944. if (ret < 0)
  1945. // for compatibility reasons, seek to the best-fitting timestamp
  1946. ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
  1947. }
  1948. return ret;
  1949. }
  1950. #else
  1951. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1952. MpegTSContext *ts = s->priv_data;
  1953. uint8_t buf[TS_PACKET_SIZE];
  1954. int64_t pos;
  1955. if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1956. return -1;
  1957. pos= avio_tell(s->pb);
  1958. for(;;) {
  1959. avio_seek(s->pb, pos, SEEK_SET);
  1960. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1961. return -1;
  1962. // pid = AV_RB16(buf + 1) & 0x1fff;
  1963. if(buf[1] & 0x40) break;
  1964. pos += ts->raw_packet_size;
  1965. }
  1966. avio_seek(s->pb, pos, SEEK_SET);
  1967. return 0;
  1968. }
  1969. #endif
  1970. /**************************************************************/
  1971. /* parsing functions - called from other demuxers such as RTP */
  1972. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1973. {
  1974. MpegTSContext *ts;
  1975. ts = av_mallocz(sizeof(MpegTSContext));
  1976. if (!ts)
  1977. return NULL;
  1978. /* no stream case, currently used by RTP */
  1979. ts->raw_packet_size = TS_PACKET_SIZE;
  1980. ts->stream = s;
  1981. ts->auto_guess = 1;
  1982. return ts;
  1983. }
  1984. /* return the consumed length if a packet was output, or -1 if no
  1985. packet is output */
  1986. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1987. const uint8_t *buf, int len)
  1988. {
  1989. int len1;
  1990. len1 = len;
  1991. ts->pkt = pkt;
  1992. ts->stop_parse = 0;
  1993. for(;;) {
  1994. if (ts->stop_parse>0)
  1995. break;
  1996. if (len < TS_PACKET_SIZE)
  1997. return -1;
  1998. if (buf[0] != 0x47) {
  1999. buf++;
  2000. len--;
  2001. } else {
  2002. handle_packet(ts, buf);
  2003. buf += TS_PACKET_SIZE;
  2004. len -= TS_PACKET_SIZE;
  2005. }
  2006. }
  2007. return len1 - len;
  2008. }
  2009. void ff_mpegts_parse_close(MpegTSContext *ts)
  2010. {
  2011. int i;
  2012. for(i=0;i<NB_PID_MAX;i++)
  2013. av_free(ts->pids[i]);
  2014. av_free(ts);
  2015. }
  2016. AVInputFormat ff_mpegts_demuxer = {
  2017. .name = "mpegts",
  2018. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  2019. .priv_data_size = sizeof(MpegTSContext),
  2020. .read_probe = mpegts_probe,
  2021. .read_header = mpegts_read_header,
  2022. .read_packet = mpegts_read_packet,
  2023. .read_close = mpegts_read_close,
  2024. .read_seek = read_seek,
  2025. .read_timestamp = mpegts_get_pcr,
  2026. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2027. #ifdef USE_SYNCPOINT_SEARCH
  2028. .read_seek2 = read_seek2,
  2029. #endif
  2030. };
  2031. AVInputFormat ff_mpegtsraw_demuxer = {
  2032. .name = "mpegtsraw",
  2033. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  2034. .priv_data_size = sizeof(MpegTSContext),
  2035. .read_header = mpegts_read_header,
  2036. .read_packet = mpegts_raw_read_packet,
  2037. .read_close = mpegts_read_close,
  2038. .read_seek = read_seek,
  2039. .read_timestamp = mpegts_get_pcr,
  2040. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2041. #ifdef USE_SYNCPOINT_SEARCH
  2042. .read_seek2 = read_seek2,
  2043. #endif
  2044. .priv_class = &mpegtsraw_class,
  2045. };