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.

2513 lines
80KB

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