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.

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