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.

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