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.

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