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.

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