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.

2598 lines
84KB

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