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.

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