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.

2222 lines
70KB

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