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.

2241 lines
71KB

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