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.

2300 lines
72KB

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