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.

2275 lines
72KB

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