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.

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