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.

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