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.

2595 lines
83KB

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