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.

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