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.

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