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.

2314 lines
73KB

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