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.

2341 lines
74KB

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