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.

2477 lines
79KB

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