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.

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