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.

2313 lines
73KB

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