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.

2270 lines
71KB

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