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.

2303 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. #if !CONFIG_LOAS_DEMUXER
  495. { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
  496. #endif
  497. { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
  498. { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  499. { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  500. { 0 },
  501. };
  502. static const StreamType HDMV_types[] = {
  503. { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
  504. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  505. { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  506. { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
  507. { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
  508. { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
  509. { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
  510. { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
  511. { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
  512. { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
  513. { 0 },
  514. };
  515. /* ATSC ? */
  516. static const StreamType MISC_types[] = {
  517. { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  518. { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  519. { 0 },
  520. };
  521. static const StreamType REGD_types[] = {
  522. { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
  523. { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
  524. { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
  525. { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  526. { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  527. { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  528. { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
  529. { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
  530. { 0 },
  531. };
  532. /* descriptor present */
  533. static const StreamType DESC_types[] = {
  534. { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
  535. { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
  536. { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
  537. { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
  538. { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
  539. { 0 },
  540. };
  541. static void mpegts_find_stream_type(AVStream *st,
  542. uint32_t stream_type, const StreamType *types)
  543. {
  544. if (avcodec_is_open(st->codec)) {
  545. av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
  546. return;
  547. }
  548. for (; types->stream_type; types++) {
  549. if (stream_type == types->stream_type) {
  550. st->codec->codec_type = types->codec_type;
  551. st->codec->codec_id = types->codec_id;
  552. st->request_probe = 0;
  553. return;
  554. }
  555. }
  556. }
  557. static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
  558. uint32_t stream_type, uint32_t prog_reg_desc)
  559. {
  560. int old_codec_type= st->codec->codec_type;
  561. int old_codec_id = st->codec->codec_id;
  562. if (avcodec_is_open(st->codec)) {
  563. av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
  564. return 0;
  565. }
  566. avpriv_set_pts_info(st, 33, 1, 90000);
  567. st->priv_data = pes;
  568. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  569. st->codec->codec_id = AV_CODEC_ID_NONE;
  570. st->need_parsing = AVSTREAM_PARSE_FULL;
  571. pes->st = st;
  572. pes->stream_type = stream_type;
  573. av_log(pes->stream, AV_LOG_DEBUG,
  574. "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
  575. st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
  576. st->codec->codec_tag = pes->stream_type;
  577. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  578. if ((prog_reg_desc == AV_RL32("HDMV") ||
  579. prog_reg_desc == AV_RL32("HDPR")) &&
  580. st->codec->codec_id == AV_CODEC_ID_NONE) {
  581. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  582. if (pes->stream_type == 0x83) {
  583. // HDMV TrueHD streams also contain an AC3 coded version of the
  584. // audio track - add a second stream for this
  585. AVStream *sub_st;
  586. // priv_data cannot be shared between streams
  587. PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
  588. if (!sub_pes)
  589. return AVERROR(ENOMEM);
  590. memcpy(sub_pes, pes, sizeof(*sub_pes));
  591. sub_st = avformat_new_stream(pes->stream, NULL);
  592. if (!sub_st) {
  593. av_free(sub_pes);
  594. return AVERROR(ENOMEM);
  595. }
  596. sub_st->id = pes->pid;
  597. avpriv_set_pts_info(sub_st, 33, 1, 90000);
  598. sub_st->priv_data = sub_pes;
  599. sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  600. sub_st->codec->codec_id = AV_CODEC_ID_AC3;
  601. sub_st->need_parsing = AVSTREAM_PARSE_FULL;
  602. sub_pes->sub_st = pes->sub_st = sub_st;
  603. }
  604. }
  605. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  606. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  607. if (st->codec->codec_id == AV_CODEC_ID_NONE){
  608. st->codec->codec_id = old_codec_id;
  609. st->codec->codec_type= old_codec_type;
  610. }
  611. return 0;
  612. }
  613. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  614. {
  615. av_init_packet(pkt);
  616. pkt->destruct = av_destruct_packet;
  617. pkt->data = pes->buffer;
  618. pkt->size = pes->data_index;
  619. if(pes->total_size != MAX_PES_PAYLOAD &&
  620. pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
  621. av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
  622. pes->flags |= AV_PKT_FLAG_CORRUPT;
  623. }
  624. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  625. // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
  626. if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
  627. pkt->stream_index = pes->sub_st->index;
  628. else
  629. pkt->stream_index = pes->st->index;
  630. pkt->pts = pes->pts;
  631. pkt->dts = pes->dts;
  632. /* store position of first TS packet of this PES packet */
  633. pkt->pos = pes->ts_packet_pos;
  634. pkt->flags = pes->flags;
  635. /* reset pts values */
  636. pes->pts = AV_NOPTS_VALUE;
  637. pes->dts = AV_NOPTS_VALUE;
  638. pes->buffer = NULL;
  639. pes->data_index = 0;
  640. pes->flags = 0;
  641. }
  642. static uint64_t get_ts64(GetBitContext *gb, int bits)
  643. {
  644. if (get_bits_left(gb) < bits)
  645. return AV_NOPTS_VALUE;
  646. return get_bits64(gb, bits);
  647. }
  648. static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
  649. {
  650. GetBitContext gb;
  651. int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
  652. int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
  653. int dts_flag = -1, cts_flag = -1;
  654. int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
  655. init_get_bits(&gb, buf, buf_size*8);
  656. if (sl->use_au_start)
  657. au_start_flag = get_bits1(&gb);
  658. if (sl->use_au_end)
  659. au_end_flag = get_bits1(&gb);
  660. if (!sl->use_au_start && !sl->use_au_end)
  661. au_start_flag = au_end_flag = 1;
  662. if (sl->ocr_len > 0)
  663. ocr_flag = get_bits1(&gb);
  664. if (sl->use_idle)
  665. idle_flag = get_bits1(&gb);
  666. if (sl->use_padding)
  667. padding_flag = get_bits1(&gb);
  668. if (padding_flag)
  669. padding_bits = get_bits(&gb, 3);
  670. if (!idle_flag && (!padding_flag || padding_bits != 0)) {
  671. if (sl->packet_seq_num_len)
  672. skip_bits_long(&gb, sl->packet_seq_num_len);
  673. if (sl->degr_prior_len)
  674. if (get_bits1(&gb))
  675. skip_bits(&gb, sl->degr_prior_len);
  676. if (ocr_flag)
  677. skip_bits_long(&gb, sl->ocr_len);
  678. if (au_start_flag) {
  679. if (sl->use_rand_acc_pt)
  680. get_bits1(&gb);
  681. if (sl->au_seq_num_len > 0)
  682. skip_bits_long(&gb, sl->au_seq_num_len);
  683. if (sl->use_timestamps) {
  684. dts_flag = get_bits1(&gb);
  685. cts_flag = get_bits1(&gb);
  686. }
  687. }
  688. if (sl->inst_bitrate_len)
  689. inst_bitrate_flag = get_bits1(&gb);
  690. if (dts_flag == 1)
  691. dts = get_ts64(&gb, sl->timestamp_len);
  692. if (cts_flag == 1)
  693. cts = get_ts64(&gb, sl->timestamp_len);
  694. if (sl->au_len > 0)
  695. skip_bits_long(&gb, sl->au_len);
  696. if (inst_bitrate_flag)
  697. skip_bits_long(&gb, sl->inst_bitrate_len);
  698. }
  699. if (dts != AV_NOPTS_VALUE)
  700. pes->dts = dts;
  701. if (cts != AV_NOPTS_VALUE)
  702. pes->pts = cts;
  703. if (sl->timestamp_len && sl->timestamp_res)
  704. avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
  705. return (get_bits_count(&gb) + 7) >> 3;
  706. }
  707. /* return non zero if a packet could be constructed */
  708. static int mpegts_push_data(MpegTSFilter *filter,
  709. const uint8_t *buf, int buf_size, int is_start,
  710. int64_t pos)
  711. {
  712. PESContext *pes = filter->u.pes_filter.opaque;
  713. MpegTSContext *ts = pes->ts;
  714. const uint8_t *p;
  715. int len, code;
  716. if(!ts->pkt)
  717. return 0;
  718. if (is_start) {
  719. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  720. new_pes_packet(pes, ts->pkt);
  721. ts->stop_parse = 1;
  722. }
  723. pes->state = MPEGTS_HEADER;
  724. pes->data_index = 0;
  725. pes->ts_packet_pos = pos;
  726. }
  727. p = buf;
  728. while (buf_size > 0) {
  729. switch(pes->state) {
  730. case MPEGTS_HEADER:
  731. len = PES_START_SIZE - pes->data_index;
  732. if (len > buf_size)
  733. len = buf_size;
  734. memcpy(pes->header + pes->data_index, p, len);
  735. pes->data_index += len;
  736. p += len;
  737. buf_size -= len;
  738. if (pes->data_index == PES_START_SIZE) {
  739. /* we got all the PES or section header. We can now
  740. decide */
  741. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  742. pes->header[2] == 0x01) {
  743. /* it must be an mpeg2 PES stream */
  744. code = pes->header[3] | 0x100;
  745. av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
  746. if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
  747. (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
  748. code == 0x1be) /* padding_stream */
  749. goto skip;
  750. /* stream not present in PMT */
  751. if (!pes->st) {
  752. pes->st = avformat_new_stream(ts->stream, NULL);
  753. if (!pes->st)
  754. return AVERROR(ENOMEM);
  755. pes->st->id = pes->pid;
  756. mpegts_set_stream_info(pes->st, pes, 0, 0);
  757. }
  758. pes->total_size = AV_RB16(pes->header + 4);
  759. /* NOTE: a zero total size means the PES size is
  760. unbounded */
  761. if (!pes->total_size)
  762. pes->total_size = MAX_PES_PAYLOAD;
  763. /* allocate pes buffer */
  764. pes->buffer = av_malloc(pes->total_size+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_malloc(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+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. av_log_missing_feature(d->s, "Predefined SLConfigDescriptor", 0);
  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. av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
  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. }
  1459. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  1460. {
  1461. MpegTSContext *ts = filter->u.section_filter.opaque;
  1462. SectionHeader h1, *h = &h1;
  1463. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  1464. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  1465. char *name, *provider_name;
  1466. av_dlog(ts->stream, "SDT:\n");
  1467. hex_dump_debug(ts->stream, section, section_len);
  1468. p_end = section + section_len - 4;
  1469. p = section;
  1470. if (parse_section_header(h, &p, p_end) < 0)
  1471. return;
  1472. if (h->tid != SDT_TID)
  1473. return;
  1474. onid = get16(&p, p_end);
  1475. if (onid < 0)
  1476. return;
  1477. val = get8(&p, p_end);
  1478. if (val < 0)
  1479. return;
  1480. for(;;) {
  1481. sid = get16(&p, p_end);
  1482. if (sid < 0)
  1483. break;
  1484. val = get8(&p, p_end);
  1485. if (val < 0)
  1486. break;
  1487. desc_list_len = get16(&p, p_end);
  1488. if (desc_list_len < 0)
  1489. break;
  1490. desc_list_len &= 0xfff;
  1491. desc_list_end = p + desc_list_len;
  1492. if (desc_list_end > p_end)
  1493. break;
  1494. for(;;) {
  1495. desc_tag = get8(&p, desc_list_end);
  1496. if (desc_tag < 0)
  1497. break;
  1498. desc_len = get8(&p, desc_list_end);
  1499. desc_end = p + desc_len;
  1500. if (desc_end > desc_list_end)
  1501. break;
  1502. av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
  1503. desc_tag, desc_len);
  1504. switch(desc_tag) {
  1505. case 0x48:
  1506. service_type = get8(&p, p_end);
  1507. if (service_type < 0)
  1508. break;
  1509. provider_name = getstr8(&p, p_end);
  1510. if (!provider_name)
  1511. break;
  1512. name = getstr8(&p, p_end);
  1513. if (name) {
  1514. AVProgram *program = av_new_program(ts->stream, sid);
  1515. if(program) {
  1516. av_dict_set(&program->metadata, "service_name", name, 0);
  1517. av_dict_set(&program->metadata, "service_provider", provider_name, 0);
  1518. }
  1519. }
  1520. av_free(name);
  1521. av_free(provider_name);
  1522. break;
  1523. default:
  1524. break;
  1525. }
  1526. p = desc_end;
  1527. }
  1528. p = desc_list_end;
  1529. }
  1530. }
  1531. /* handle one TS packet */
  1532. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  1533. {
  1534. AVFormatContext *s = ts->stream;
  1535. MpegTSFilter *tss;
  1536. int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
  1537. has_adaptation, has_payload;
  1538. const uint8_t *p, *p_end;
  1539. int64_t pos;
  1540. pid = AV_RB16(packet + 1) & 0x1fff;
  1541. if(pid && discard_pid(ts, pid))
  1542. return 0;
  1543. is_start = packet[1] & 0x40;
  1544. tss = ts->pids[pid];
  1545. if (ts->auto_guess && tss == NULL && is_start) {
  1546. add_pes_stream(ts, pid, -1);
  1547. tss = ts->pids[pid];
  1548. }
  1549. if (!tss)
  1550. return 0;
  1551. ts->current_pid = pid;
  1552. afc = (packet[3] >> 4) & 3;
  1553. if (afc == 0) /* reserved value */
  1554. return 0;
  1555. has_adaptation = afc & 2;
  1556. has_payload = afc & 1;
  1557. is_discontinuity = has_adaptation
  1558. && packet[4] != 0 /* with length > 0 */
  1559. && (packet[5] & 0x80); /* and discontinuity indicated */
  1560. /* continuity check (currently not used) */
  1561. cc = (packet[3] & 0xf);
  1562. expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
  1563. cc_ok = pid == 0x1FFF // null packet PID
  1564. || is_discontinuity
  1565. || tss->last_cc < 0
  1566. || expected_cc == cc;
  1567. tss->last_cc = cc;
  1568. if (!cc_ok) {
  1569. av_log(ts->stream, AV_LOG_DEBUG,
  1570. "Continuity check failed for pid %d expected %d got %d\n",
  1571. pid, expected_cc, cc);
  1572. if(tss->type == MPEGTS_PES) {
  1573. PESContext *pc = tss->u.pes_filter.opaque;
  1574. pc->flags |= AV_PKT_FLAG_CORRUPT;
  1575. }
  1576. }
  1577. if (!has_payload)
  1578. return 0;
  1579. p = packet + 4;
  1580. if (has_adaptation) {
  1581. /* skip adaptation field */
  1582. p += p[0] + 1;
  1583. }
  1584. /* if past the end of packet, ignore */
  1585. p_end = packet + TS_PACKET_SIZE;
  1586. if (p >= p_end)
  1587. return 0;
  1588. pos = avio_tell(ts->stream->pb);
  1589. ts->pos47= pos % ts->raw_packet_size;
  1590. if (tss->type == MPEGTS_SECTION) {
  1591. if (is_start) {
  1592. /* pointer field present */
  1593. len = *p++;
  1594. if (p + len > p_end)
  1595. return 0;
  1596. if (len && cc_ok) {
  1597. /* write remaining section bytes */
  1598. write_section_data(s, tss,
  1599. p, len, 0);
  1600. /* check whether filter has been closed */
  1601. if (!ts->pids[pid])
  1602. return 0;
  1603. }
  1604. p += len;
  1605. if (p < p_end) {
  1606. write_section_data(s, tss,
  1607. p, p_end - p, 1);
  1608. }
  1609. } else {
  1610. if (cc_ok) {
  1611. write_section_data(s, tss,
  1612. p, p_end - p, 0);
  1613. }
  1614. }
  1615. } else {
  1616. int ret;
  1617. // Note: The position here points actually behind the current packet.
  1618. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  1619. pos - ts->raw_packet_size)) < 0)
  1620. return ret;
  1621. }
  1622. return 0;
  1623. }
  1624. /* XXX: try to find a better synchro over several packets (use
  1625. get_packet_size() ?) */
  1626. static int mpegts_resync(AVFormatContext *s)
  1627. {
  1628. AVIOContext *pb = s->pb;
  1629. int c, i;
  1630. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  1631. c = avio_r8(pb);
  1632. if (url_feof(pb))
  1633. return -1;
  1634. if (c == 0x47) {
  1635. avio_seek(pb, -1, SEEK_CUR);
  1636. return 0;
  1637. }
  1638. }
  1639. av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
  1640. /* no sync found */
  1641. return -1;
  1642. }
  1643. /* return -1 if error or EOF. Return 0 if OK. */
  1644. static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
  1645. {
  1646. AVIOContext *pb = s->pb;
  1647. int skip, len;
  1648. for(;;) {
  1649. len = avio_read(pb, buf, TS_PACKET_SIZE);
  1650. if (len != TS_PACKET_SIZE)
  1651. return len < 0 ? len : AVERROR_EOF;
  1652. /* check packet sync byte */
  1653. if (buf[0] != 0x47) {
  1654. /* find a new packet start */
  1655. avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1656. if (mpegts_resync(s) < 0)
  1657. return AVERROR(EAGAIN);
  1658. else
  1659. continue;
  1660. } else {
  1661. skip = raw_packet_size - TS_PACKET_SIZE;
  1662. if (skip > 0)
  1663. avio_skip(pb, skip);
  1664. break;
  1665. }
  1666. }
  1667. return 0;
  1668. }
  1669. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1670. {
  1671. AVFormatContext *s = ts->stream;
  1672. uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  1673. int packet_num, ret = 0;
  1674. if (avio_tell(s->pb) != ts->last_pos) {
  1675. int i;
  1676. av_dlog(ts->stream, "Skipping after seek\n");
  1677. /* seek detected, flush pes buffer */
  1678. for (i = 0; i < NB_PID_MAX; i++) {
  1679. if (ts->pids[i]) {
  1680. if (ts->pids[i]->type == MPEGTS_PES) {
  1681. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1682. av_freep(&pes->buffer);
  1683. pes->data_index = 0;
  1684. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1685. }
  1686. ts->pids[i]->last_cc = -1;
  1687. }
  1688. }
  1689. }
  1690. ts->stop_parse = 0;
  1691. packet_num = 0;
  1692. memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  1693. for(;;) {
  1694. packet_num++;
  1695. if (nb_packets != 0 && packet_num >= nb_packets ||
  1696. ts->stop_parse > 1) {
  1697. ret = AVERROR(EAGAIN);
  1698. break;
  1699. }
  1700. if (ts->stop_parse > 0)
  1701. break;
  1702. ret = read_packet(s, packet, ts->raw_packet_size);
  1703. if (ret != 0)
  1704. break;
  1705. ret = handle_packet(ts, packet);
  1706. if (ret != 0)
  1707. break;
  1708. }
  1709. ts->last_pos = avio_tell(s->pb);
  1710. return ret;
  1711. }
  1712. static int mpegts_probe(AVProbeData *p)
  1713. {
  1714. const int size= p->buf_size;
  1715. int maxscore=0;
  1716. int sumscore=0;
  1717. int i;
  1718. int check_count= size / TS_FEC_PACKET_SIZE;
  1719. #define CHECK_COUNT 10
  1720. #define CHECK_BLOCK 100
  1721. if (check_count < CHECK_COUNT)
  1722. return -1;
  1723. for (i=0; i<check_count; i+=CHECK_BLOCK){
  1724. int left = FFMIN(check_count - i, CHECK_BLOCK);
  1725. int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
  1726. int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
  1727. int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
  1728. score = FFMAX3(score, dvhs_score, fec_score);
  1729. sumscore += score;
  1730. maxscore = FFMAX(maxscore, score);
  1731. }
  1732. sumscore = sumscore*CHECK_COUNT/check_count;
  1733. maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
  1734. av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
  1735. if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
  1736. else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
  1737. else return -1;
  1738. }
  1739. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1740. (-1) if not available */
  1741. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1742. const uint8_t *packet)
  1743. {
  1744. int afc, len, flags;
  1745. const uint8_t *p;
  1746. unsigned int v;
  1747. afc = (packet[3] >> 4) & 3;
  1748. if (afc <= 1)
  1749. return -1;
  1750. p = packet + 4;
  1751. len = p[0];
  1752. p++;
  1753. if (len == 0)
  1754. return -1;
  1755. flags = *p++;
  1756. len--;
  1757. if (!(flags & 0x10))
  1758. return -1;
  1759. if (len < 6)
  1760. return -1;
  1761. v = AV_RB32(p);
  1762. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1763. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1764. return 0;
  1765. }
  1766. static int mpegts_read_header(AVFormatContext *s)
  1767. {
  1768. MpegTSContext *ts = s->priv_data;
  1769. AVIOContext *pb = s->pb;
  1770. uint8_t buf[8*1024]={0};
  1771. int len;
  1772. int64_t pos;
  1773. /* read the first 8192 bytes to get packet size */
  1774. pos = avio_tell(pb);
  1775. len = avio_read(pb, buf, sizeof(buf));
  1776. ts->raw_packet_size = get_packet_size(buf, len);
  1777. if (ts->raw_packet_size <= 0) {
  1778. av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
  1779. ts->raw_packet_size = TS_PACKET_SIZE;
  1780. }
  1781. ts->stream = s;
  1782. ts->auto_guess = 0;
  1783. if (s->iformat == &ff_mpegts_demuxer) {
  1784. /* normal demux */
  1785. /* first do a scan to get all the services */
  1786. /* NOTE: We attempt to seek on non-seekable files as well, as the
  1787. * probe buffer usually is big enough. Only warn if the seek failed
  1788. * on files where the seek should work. */
  1789. if (avio_seek(pb, pos, SEEK_SET) < 0)
  1790. av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
  1791. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1792. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1793. handle_packets(ts, s->probesize / ts->raw_packet_size);
  1794. /* if could not find service, enable auto_guess */
  1795. ts->auto_guess = 1;
  1796. av_dlog(ts->stream, "tuning done\n");
  1797. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1798. } else {
  1799. AVStream *st;
  1800. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1801. int64_t pcrs[2], pcr_h;
  1802. int packet_count[2];
  1803. uint8_t packet[TS_PACKET_SIZE];
  1804. /* only read packets */
  1805. st = avformat_new_stream(s, NULL);
  1806. if (!st)
  1807. goto fail;
  1808. avpriv_set_pts_info(st, 60, 1, 27000000);
  1809. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1810. st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
  1811. /* we iterate until we find two PCRs to estimate the bitrate */
  1812. pcr_pid = -1;
  1813. nb_pcrs = 0;
  1814. nb_packets = 0;
  1815. for(;;) {
  1816. ret = read_packet(s, packet, ts->raw_packet_size);
  1817. if (ret < 0)
  1818. return -1;
  1819. pid = AV_RB16(packet + 1) & 0x1fff;
  1820. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1821. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1822. pcr_pid = pid;
  1823. packet_count[nb_pcrs] = nb_packets;
  1824. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1825. nb_pcrs++;
  1826. if (nb_pcrs >= 2)
  1827. break;
  1828. }
  1829. nb_packets++;
  1830. }
  1831. /* NOTE1: the bitrate is computed without the FEC */
  1832. /* NOTE2: it is only the bitrate of the start of the stream */
  1833. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1834. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1835. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1836. st->codec->bit_rate = s->bit_rate;
  1837. st->start_time = ts->cur_pcr;
  1838. av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
  1839. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1840. }
  1841. avio_seek(pb, pos, SEEK_SET);
  1842. return 0;
  1843. fail:
  1844. return -1;
  1845. }
  1846. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1847. static int mpegts_raw_read_packet(AVFormatContext *s,
  1848. AVPacket *pkt)
  1849. {
  1850. MpegTSContext *ts = s->priv_data;
  1851. int ret, i;
  1852. int64_t pcr_h, next_pcr_h, pos;
  1853. int pcr_l, next_pcr_l;
  1854. uint8_t pcr_buf[12];
  1855. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1856. return AVERROR(ENOMEM);
  1857. pkt->pos= avio_tell(s->pb);
  1858. ret = read_packet(s, pkt->data, ts->raw_packet_size);
  1859. if (ret < 0) {
  1860. av_free_packet(pkt);
  1861. return ret;
  1862. }
  1863. if (ts->mpeg2ts_compute_pcr) {
  1864. /* compute exact PCR for each packet */
  1865. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1866. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1867. pos = avio_tell(s->pb);
  1868. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1869. avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1870. avio_read(s->pb, pcr_buf, 12);
  1871. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1872. /* XXX: not precise enough */
  1873. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1874. (i + 1);
  1875. break;
  1876. }
  1877. }
  1878. avio_seek(s->pb, pos, SEEK_SET);
  1879. /* no next PCR found: we use previous increment */
  1880. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1881. }
  1882. pkt->pts = ts->cur_pcr;
  1883. pkt->duration = ts->pcr_incr;
  1884. ts->cur_pcr += ts->pcr_incr;
  1885. }
  1886. pkt->stream_index = 0;
  1887. return 0;
  1888. }
  1889. static int mpegts_read_packet(AVFormatContext *s,
  1890. AVPacket *pkt)
  1891. {
  1892. MpegTSContext *ts = s->priv_data;
  1893. int ret, i;
  1894. pkt->size = -1;
  1895. ts->pkt = pkt;
  1896. ret = handle_packets(ts, 0);
  1897. if (ret < 0) {
  1898. av_free_packet(ts->pkt);
  1899. /* flush pes data left */
  1900. for (i = 0; i < NB_PID_MAX; i++) {
  1901. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1902. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1903. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1904. new_pes_packet(pes, pkt);
  1905. pes->state = MPEGTS_SKIP;
  1906. ret = 0;
  1907. break;
  1908. }
  1909. }
  1910. }
  1911. }
  1912. if (!ret && pkt->size < 0)
  1913. ret = AVERROR(EINTR);
  1914. return ret;
  1915. }
  1916. static void mpegts_free(MpegTSContext *ts)
  1917. {
  1918. int i;
  1919. clear_programs(ts);
  1920. for(i=0;i<NB_PID_MAX;i++)
  1921. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1922. }
  1923. static int mpegts_read_close(AVFormatContext *s)
  1924. {
  1925. MpegTSContext *ts = s->priv_data;
  1926. mpegts_free(ts);
  1927. return 0;
  1928. }
  1929. static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1930. int64_t *ppos, int64_t pos_limit)
  1931. {
  1932. MpegTSContext *ts = s->priv_data;
  1933. int64_t pos, timestamp;
  1934. uint8_t buf[TS_PACKET_SIZE];
  1935. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1936. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1937. while(pos < pos_limit) {
  1938. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  1939. return AV_NOPTS_VALUE;
  1940. if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1941. return AV_NOPTS_VALUE;
  1942. if (buf[0] != 0x47) {
  1943. if (mpegts_resync(s) < 0)
  1944. return AV_NOPTS_VALUE;
  1945. pos = avio_tell(s->pb);
  1946. continue;
  1947. }
  1948. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1949. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1950. *ppos = pos;
  1951. return timestamp;
  1952. }
  1953. pos += ts->raw_packet_size;
  1954. }
  1955. return AV_NOPTS_VALUE;
  1956. }
  1957. static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
  1958. int64_t *ppos, int64_t pos_limit)
  1959. {
  1960. MpegTSContext *ts = s->priv_data;
  1961. int64_t pos;
  1962. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1963. ff_read_frame_flush(s);
  1964. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  1965. return AV_NOPTS_VALUE;
  1966. while(pos < pos_limit) {
  1967. int ret;
  1968. AVPacket pkt;
  1969. av_init_packet(&pkt);
  1970. ret= av_read_frame(s, &pkt);
  1971. if(ret < 0)
  1972. return AV_NOPTS_VALUE;
  1973. av_free_packet(&pkt);
  1974. if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
  1975. ff_reduce_index(s, pkt.stream_index);
  1976. av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  1977. if(pkt.stream_index == stream_index){
  1978. *ppos= pkt.pos;
  1979. return pkt.dts;
  1980. }
  1981. }
  1982. pos = pkt.pos;
  1983. }
  1984. return AV_NOPTS_VALUE;
  1985. }
  1986. /**************************************************************/
  1987. /* parsing functions - called from other demuxers such as RTP */
  1988. MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
  1989. {
  1990. MpegTSContext *ts;
  1991. ts = av_mallocz(sizeof(MpegTSContext));
  1992. if (!ts)
  1993. return NULL;
  1994. /* no stream case, currently used by RTP */
  1995. ts->raw_packet_size = TS_PACKET_SIZE;
  1996. ts->stream = s;
  1997. ts->auto_guess = 1;
  1998. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1999. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  2000. return ts;
  2001. }
  2002. /* return the consumed length if a packet was output, or -1 if no
  2003. packet is output */
  2004. int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  2005. const uint8_t *buf, int len)
  2006. {
  2007. int len1;
  2008. len1 = len;
  2009. ts->pkt = pkt;
  2010. for(;;) {
  2011. ts->stop_parse = 0;
  2012. if (len < TS_PACKET_SIZE)
  2013. return -1;
  2014. if (buf[0] != 0x47) {
  2015. buf++;
  2016. len--;
  2017. } else {
  2018. handle_packet(ts, buf);
  2019. buf += TS_PACKET_SIZE;
  2020. len -= TS_PACKET_SIZE;
  2021. if (ts->stop_parse == 1)
  2022. break;
  2023. }
  2024. }
  2025. return len1 - len;
  2026. }
  2027. void ff_mpegts_parse_close(MpegTSContext *ts)
  2028. {
  2029. mpegts_free(ts);
  2030. av_free(ts);
  2031. }
  2032. AVInputFormat ff_mpegts_demuxer = {
  2033. .name = "mpegts",
  2034. .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
  2035. .priv_data_size = sizeof(MpegTSContext),
  2036. .read_probe = mpegts_probe,
  2037. .read_header = mpegts_read_header,
  2038. .read_packet = mpegts_read_packet,
  2039. .read_close = mpegts_read_close,
  2040. .read_timestamp = mpegts_get_dts,
  2041. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2042. };
  2043. AVInputFormat ff_mpegtsraw_demuxer = {
  2044. .name = "mpegtsraw",
  2045. .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
  2046. .priv_data_size = sizeof(MpegTSContext),
  2047. .read_header = mpegts_read_header,
  2048. .read_packet = mpegts_raw_read_packet,
  2049. .read_close = mpegts_read_close,
  2050. .read_timestamp = mpegts_get_dts,
  2051. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  2052. .priv_class = &mpegtsraw_class,
  2053. };