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.

2341 lines
74KB

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