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.

2522 lines
81KB

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