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.

1586 lines
46KB

  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. //#define DEBUG
  22. //#define DEBUG_SEEK
  23. #include "libavutil/crc.h"
  24. #include "libavutil/intreadwrite.h"
  25. #include "libavcodec/bytestream.h"
  26. #include "avformat.h"
  27. #include "mpegts.h"
  28. #include "internal.h"
  29. /* 1.0 second at 24Mbit/s */
  30. #define MAX_SCAN_PACKETS 32000
  31. /* maximum size in which we look for synchronisation if
  32. synchronisation is lost */
  33. #define MAX_RESYNC_SIZE 4096
  34. #define MAX_PES_PAYLOAD 200*1024
  35. typedef struct PESContext PESContext;
  36. static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
  37. static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code, uint32_t prog_reg_desc, uint32_t reg_desc);
  38. enum MpegTSFilterType {
  39. MPEGTS_PES,
  40. MPEGTS_SECTION,
  41. };
  42. typedef struct MpegTSFilter MpegTSFilter;
  43. typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
  44. typedef struct MpegTSPESFilter {
  45. PESCallback *pes_cb;
  46. void *opaque;
  47. } MpegTSPESFilter;
  48. typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
  49. typedef void SetServiceCallback(void *opaque, int ret);
  50. typedef struct MpegTSSectionFilter {
  51. int section_index;
  52. int section_h_size;
  53. uint8_t *section_buf;
  54. unsigned int check_crc:1;
  55. unsigned int end_of_section_reached:1;
  56. SectionCallback *section_cb;
  57. void *opaque;
  58. } MpegTSSectionFilter;
  59. struct MpegTSFilter {
  60. int pid;
  61. int last_cc; /* last cc code (-1 if first packet) */
  62. enum MpegTSFilterType type;
  63. union {
  64. MpegTSPESFilter pes_filter;
  65. MpegTSSectionFilter section_filter;
  66. } u;
  67. };
  68. #define MAX_PIDS_PER_PROGRAM 64
  69. struct Program {
  70. unsigned int id; //program id/service id
  71. unsigned int nb_pids;
  72. unsigned int pids[MAX_PIDS_PER_PROGRAM];
  73. };
  74. struct MpegTSContext {
  75. /* user data */
  76. AVFormatContext *stream;
  77. /** raw packet size, including FEC if present */
  78. int raw_packet_size;
  79. int pos47;
  80. /** if true, all pids are analyzed to find streams */
  81. int auto_guess;
  82. /** compute exact PCR for each transport stream packet */
  83. int mpeg2ts_compute_pcr;
  84. int64_t cur_pcr; /**< used to estimate the exact PCR */
  85. int pcr_incr; /**< used to estimate the exact PCR */
  86. /* data needed to handle file based ts */
  87. /** stop parsing loop */
  88. int stop_parse;
  89. /** packet containing Audio/Video data */
  90. AVPacket *pkt;
  91. /** to detect seek */
  92. int64_t last_pos;
  93. /******************************************/
  94. /* private mpegts data */
  95. /* scan context */
  96. /** structure to keep track of Program->pids mapping */
  97. unsigned int nb_prg;
  98. struct Program *prg;
  99. /** filters for various streams specified by PMT + for the PAT and PMT */
  100. MpegTSFilter *pids[NB_PID_MAX];
  101. };
  102. /* TS stream handling */
  103. enum MpegTSState {
  104. MPEGTS_HEADER = 0,
  105. MPEGTS_PESHEADER_FILL,
  106. MPEGTS_PAYLOAD,
  107. MPEGTS_SKIP,
  108. };
  109. /* enough for PES header + length */
  110. #define PES_START_SIZE 9
  111. #define MAX_PES_HEADER_SIZE (9 + 255)
  112. struct PESContext {
  113. int pid;
  114. int pcr_pid; /**< if -1 then all packets containing PCR are considered */
  115. int stream_type;
  116. MpegTSContext *ts;
  117. AVFormatContext *stream;
  118. AVStream *st;
  119. enum MpegTSState state;
  120. /* used to get the format */
  121. int data_index;
  122. int total_size;
  123. int pes_header_size;
  124. int64_t pts, dts;
  125. int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
  126. uint8_t header[MAX_PES_HEADER_SIZE];
  127. uint8_t *buffer;
  128. };
  129. extern AVInputFormat mpegts_demuxer;
  130. static void clear_program(MpegTSContext *ts, unsigned int programid)
  131. {
  132. int i;
  133. for(i=0; i<ts->nb_prg; i++)
  134. if(ts->prg[i].id == programid)
  135. ts->prg[i].nb_pids = 0;
  136. }
  137. static void clear_programs(MpegTSContext *ts)
  138. {
  139. av_freep(&ts->prg);
  140. ts->nb_prg=0;
  141. }
  142. static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
  143. {
  144. struct Program *p;
  145. void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
  146. if(!tmp)
  147. return;
  148. ts->prg = tmp;
  149. p = &ts->prg[ts->nb_prg];
  150. p->id = programid;
  151. p->nb_pids = 0;
  152. ts->nb_prg++;
  153. }
  154. static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
  155. {
  156. int i;
  157. struct Program *p = NULL;
  158. for(i=0; i<ts->nb_prg; i++) {
  159. if(ts->prg[i].id == programid) {
  160. p = &ts->prg[i];
  161. break;
  162. }
  163. }
  164. if(!p)
  165. return;
  166. if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
  167. return;
  168. p->pids[p->nb_pids++] = pid;
  169. }
  170. /**
  171. * \brief discard_pid() decides if the pid is to be discarded according
  172. * to caller's programs selection
  173. * \param ts : - TS context
  174. * \param pid : - pid
  175. * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  176. * 0 otherwise
  177. */
  178. static int discard_pid(MpegTSContext *ts, unsigned int pid)
  179. {
  180. int i, j, k;
  181. int used = 0, discarded = 0;
  182. struct Program *p;
  183. for(i=0; i<ts->nb_prg; i++) {
  184. p = &ts->prg[i];
  185. for(j=0; j<p->nb_pids; j++) {
  186. if(p->pids[j] != pid)
  187. continue;
  188. //is program with id p->id set to be discarded?
  189. for(k=0; k<ts->stream->nb_programs; k++) {
  190. if(ts->stream->programs[k]->id == p->id) {
  191. if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
  192. discarded++;
  193. else
  194. used++;
  195. }
  196. }
  197. }
  198. }
  199. return !used && discarded;
  200. }
  201. /**
  202. * Assembles PES packets out of TS packets, and then calls the "section_cb"
  203. * function when they are complete.
  204. */
  205. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  206. const uint8_t *buf, int buf_size, int is_start)
  207. {
  208. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  209. int len;
  210. if (is_start) {
  211. memcpy(tss->section_buf, buf, buf_size);
  212. tss->section_index = buf_size;
  213. tss->section_h_size = -1;
  214. tss->end_of_section_reached = 0;
  215. } else {
  216. if (tss->end_of_section_reached)
  217. return;
  218. len = 4096 - tss->section_index;
  219. if (buf_size < len)
  220. len = buf_size;
  221. memcpy(tss->section_buf + tss->section_index, buf, len);
  222. tss->section_index += len;
  223. }
  224. /* compute section length if possible */
  225. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  226. len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
  227. if (len > 4096)
  228. return;
  229. tss->section_h_size = len;
  230. }
  231. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  232. tss->end_of_section_reached = 1;
  233. if (!tss->check_crc ||
  234. av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
  235. tss->section_buf, tss->section_h_size) == 0)
  236. tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
  237. }
  238. }
  239. static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  240. SectionCallback *section_cb, void *opaque,
  241. int check_crc)
  242. {
  243. MpegTSFilter *filter;
  244. MpegTSSectionFilter *sec;
  245. dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
  246. if (pid >= NB_PID_MAX || ts->pids[pid])
  247. return NULL;
  248. filter = av_mallocz(sizeof(MpegTSFilter));
  249. if (!filter)
  250. return NULL;
  251. ts->pids[pid] = filter;
  252. filter->type = MPEGTS_SECTION;
  253. filter->pid = pid;
  254. filter->last_cc = -1;
  255. sec = &filter->u.section_filter;
  256. sec->section_cb = section_cb;
  257. sec->opaque = opaque;
  258. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  259. sec->check_crc = check_crc;
  260. if (!sec->section_buf) {
  261. av_free(filter);
  262. return NULL;
  263. }
  264. return filter;
  265. }
  266. static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  267. PESCallback *pes_cb,
  268. void *opaque)
  269. {
  270. MpegTSFilter *filter;
  271. MpegTSPESFilter *pes;
  272. if (pid >= NB_PID_MAX || ts->pids[pid])
  273. return NULL;
  274. filter = av_mallocz(sizeof(MpegTSFilter));
  275. if (!filter)
  276. return NULL;
  277. ts->pids[pid] = filter;
  278. filter->type = MPEGTS_PES;
  279. filter->pid = pid;
  280. filter->last_cc = -1;
  281. pes = &filter->u.pes_filter;
  282. pes->pes_cb = pes_cb;
  283. pes->opaque = opaque;
  284. return filter;
  285. }
  286. static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  287. {
  288. int pid;
  289. pid = filter->pid;
  290. if (filter->type == MPEGTS_SECTION)
  291. av_freep(&filter->u.section_filter.section_buf);
  292. else if (filter->type == MPEGTS_PES) {
  293. PESContext *pes = filter->u.pes_filter.opaque;
  294. av_freep(&pes->buffer);
  295. /* referenced private data will be freed later in
  296. * av_close_input_stream */
  297. if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
  298. av_freep(&filter->u.pes_filter.opaque);
  299. }
  300. }
  301. av_free(filter);
  302. ts->pids[pid] = NULL;
  303. }
  304. static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
  305. int stat[packet_size];
  306. int i;
  307. int x=0;
  308. int best_score=0;
  309. memset(stat, 0, packet_size*sizeof(int));
  310. for(x=i=0; i<size-3; i++){
  311. if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
  312. stat[x]++;
  313. if(stat[x] > best_score){
  314. best_score= stat[x];
  315. if(index) *index= x;
  316. }
  317. }
  318. x++;
  319. if(x == packet_size) x= 0;
  320. }
  321. return best_score;
  322. }
  323. /* autodetect fec presence. Must have at least 1024 bytes */
  324. static int get_packet_size(const uint8_t *buf, int size)
  325. {
  326. int score, fec_score, dvhs_score;
  327. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  328. return -1;
  329. score = analyze(buf, size, TS_PACKET_SIZE, NULL);
  330. dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
  331. fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
  332. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  333. if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
  334. else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
  335. else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
  336. else return -1;
  337. }
  338. typedef struct SectionHeader {
  339. uint8_t tid;
  340. uint16_t id;
  341. uint8_t version;
  342. uint8_t sec_num;
  343. uint8_t last_sec_num;
  344. } SectionHeader;
  345. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  346. {
  347. const uint8_t *p;
  348. int c;
  349. p = *pp;
  350. if (p >= p_end)
  351. return -1;
  352. c = *p++;
  353. *pp = p;
  354. return c;
  355. }
  356. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  357. {
  358. const uint8_t *p;
  359. int c;
  360. p = *pp;
  361. if ((p + 1) >= p_end)
  362. return -1;
  363. c = AV_RB16(p);
  364. p += 2;
  365. *pp = p;
  366. return c;
  367. }
  368. /* read and allocate a DVB string preceeded by its length */
  369. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  370. {
  371. int len;
  372. const uint8_t *p;
  373. char *str;
  374. p = *pp;
  375. len = get8(&p, p_end);
  376. if (len < 0)
  377. return NULL;
  378. if ((p + len) > p_end)
  379. return NULL;
  380. str = av_malloc(len + 1);
  381. if (!str)
  382. return NULL;
  383. memcpy(str, p, len);
  384. str[len] = '\0';
  385. p += len;
  386. *pp = p;
  387. return str;
  388. }
  389. static int parse_section_header(SectionHeader *h,
  390. const uint8_t **pp, const uint8_t *p_end)
  391. {
  392. int val;
  393. val = get8(pp, p_end);
  394. if (val < 0)
  395. return -1;
  396. h->tid = val;
  397. *pp += 2;
  398. val = get16(pp, p_end);
  399. if (val < 0)
  400. return -1;
  401. h->id = val;
  402. val = get8(pp, p_end);
  403. if (val < 0)
  404. return -1;
  405. h->version = (val >> 1) & 0x1f;
  406. val = get8(pp, p_end);
  407. if (val < 0)
  408. return -1;
  409. h->sec_num = val;
  410. val = get8(pp, p_end);
  411. if (val < 0)
  412. return -1;
  413. h->last_sec_num = val;
  414. return 0;
  415. }
  416. static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  417. {
  418. MpegTSContext *ts = filter->u.section_filter.opaque;
  419. SectionHeader h1, *h = &h1;
  420. PESContext *pes;
  421. AVStream *st;
  422. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  423. int program_info_length, pcr_pid, pid, stream_type;
  424. int desc_list_len, desc_len, desc_tag;
  425. int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
  426. char language[4] = {0}; /* initialize to kill warnings */
  427. uint32_t prog_reg_desc = 0; /* registration descriptor */
  428. uint32_t reg_desc = 0; /* registration descriptor */
  429. #ifdef DEBUG
  430. dprintf(ts->stream, "PMT: len %i\n", section_len);
  431. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  432. #endif
  433. p_end = section + section_len - 4;
  434. p = section;
  435. if (parse_section_header(h, &p, p_end) < 0)
  436. return;
  437. dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
  438. h->id, h->sec_num, h->last_sec_num);
  439. if (h->tid != PMT_TID)
  440. return;
  441. clear_program(ts, h->id);
  442. pcr_pid = get16(&p, p_end) & 0x1fff;
  443. if (pcr_pid < 0)
  444. return;
  445. add_pid_to_pmt(ts, h->id, pcr_pid);
  446. dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
  447. program_info_length = get16(&p, p_end) & 0xfff;
  448. if (program_info_length < 0)
  449. return;
  450. while(program_info_length >= 2) {
  451. uint8_t tag, len;
  452. tag = get8(&p, p_end);
  453. len = get8(&p, p_end);
  454. if(len > program_info_length - 2)
  455. //something else is broken, exit the program_descriptors_loop
  456. break;
  457. program_info_length -= len + 2;
  458. if(tag == 0x05 && len >= 4) { // registration descriptor
  459. prog_reg_desc = bytestream_get_le32(&p);
  460. len -= 4;
  461. }
  462. p += len;
  463. }
  464. p += program_info_length;
  465. if (p >= p_end)
  466. return;
  467. for(;;) {
  468. reg_desc = 0;
  469. language[0] = 0;
  470. st = 0;
  471. stream_type = get8(&p, p_end);
  472. if (stream_type < 0)
  473. break;
  474. pid = get16(&p, p_end) & 0x1fff;
  475. if (pid < 0)
  476. break;
  477. desc_list_len = get16(&p, p_end) & 0xfff;
  478. if (desc_list_len < 0)
  479. break;
  480. desc_list_end = p + desc_list_len;
  481. if (desc_list_end > p_end)
  482. break;
  483. for(;;) {
  484. desc_tag = get8(&p, desc_list_end);
  485. if (desc_tag < 0)
  486. break;
  487. if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
  488. if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
  489. /*assume DVB AC-3 Audio*/
  490. stream_type = STREAM_TYPE_AUDIO_AC3;
  491. } else if(desc_tag == 0x7B) {
  492. /* DVB DTS audio */
  493. stream_type = STREAM_TYPE_AUDIO_DTS;
  494. }
  495. }
  496. desc_len = get8(&p, desc_list_end);
  497. if (desc_len < 0)
  498. break;
  499. desc_end = p + desc_len;
  500. if (desc_end > desc_list_end)
  501. break;
  502. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  503. desc_tag, desc_len);
  504. switch(desc_tag) {
  505. case 0x59: /* subtitling descriptor */
  506. if (stream_type == STREAM_TYPE_PRIVATE_DATA)
  507. stream_type = 0x100; // demuxer internal
  508. language[0] = get8(&p, desc_end);
  509. language[1] = get8(&p, desc_end);
  510. language[2] = get8(&p, desc_end);
  511. language[3] = 0;
  512. get8(&p, desc_end);
  513. comp_page = get16(&p, desc_end);
  514. anc_page = get16(&p, desc_end);
  515. break;
  516. case 0x0a: /* ISO 639 language descriptor */
  517. language[0] = get8(&p, desc_end);
  518. language[1] = get8(&p, desc_end);
  519. language[2] = get8(&p, desc_end);
  520. language[3] = 0;
  521. break;
  522. case 0x05: /* registration descriptor */
  523. reg_desc = bytestream_get_le32(&p);
  524. break;
  525. default:
  526. break;
  527. }
  528. p = desc_end;
  529. }
  530. p = desc_list_end;
  531. dprintf(ts->stream, "stream_type=%x pid=0x%x\n",
  532. stream_type, pid);
  533. /* now create ffmpeg stream */
  534. if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
  535. pes= ts->pids[pid]->u.pes_filter.opaque;
  536. st= pes->st;
  537. } else {
  538. if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
  539. pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
  540. if (pes)
  541. st = new_pes_av_stream(pes, 0, prog_reg_desc, reg_desc);
  542. }
  543. add_pid_to_pmt(ts, h->id, pid);
  544. if(st) {
  545. av_program_add_stream_index(ts->stream, h->id, st->index);
  546. if (language[0] != 0)
  547. av_metadata_set(&st->metadata, "language", language);
  548. if (stream_type == 0x100)
  549. st->codec->sub_id = (anc_page << 16) | comp_page;
  550. }
  551. }
  552. /* all parameters are there */
  553. ts->stop_parse++;
  554. mpegts_close_filter(ts, filter);
  555. }
  556. static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  557. {
  558. MpegTSContext *ts = filter->u.section_filter.opaque;
  559. SectionHeader h1, *h = &h1;
  560. const uint8_t *p, *p_end;
  561. int sid, pmt_pid;
  562. #ifdef DEBUG
  563. dprintf(ts->stream, "PAT:\n");
  564. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  565. #endif
  566. p_end = section + section_len - 4;
  567. p = section;
  568. if (parse_section_header(h, &p, p_end) < 0)
  569. return;
  570. if (h->tid != PAT_TID)
  571. return;
  572. clear_programs(ts);
  573. for(;;) {
  574. sid = get16(&p, p_end);
  575. if (sid < 0)
  576. break;
  577. pmt_pid = get16(&p, p_end) & 0x1fff;
  578. if (pmt_pid < 0)
  579. break;
  580. dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
  581. if (sid == 0x0000) {
  582. /* NIT info */
  583. } else {
  584. av_new_program(ts->stream, sid);
  585. ts->stop_parse--;
  586. mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
  587. add_pat_entry(ts, sid);
  588. add_pid_to_pmt(ts, sid, 0); //add pat pid to program
  589. add_pid_to_pmt(ts, sid, pmt_pid);
  590. }
  591. }
  592. /* not found */
  593. ts->stop_parse++;
  594. mpegts_close_filter(ts, filter);
  595. }
  596. static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
  597. {
  598. MpegTSContext *ts = filter->u.section_filter.opaque;
  599. SectionHeader h1, *h = &h1;
  600. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  601. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  602. char *name, *provider_name;
  603. #ifdef DEBUG
  604. dprintf(ts->stream, "SDT:\n");
  605. av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
  606. #endif
  607. p_end = section + section_len - 4;
  608. p = section;
  609. if (parse_section_header(h, &p, p_end) < 0)
  610. return;
  611. if (h->tid != SDT_TID)
  612. return;
  613. onid = get16(&p, p_end);
  614. if (onid < 0)
  615. return;
  616. val = get8(&p, p_end);
  617. if (val < 0)
  618. return;
  619. for(;;) {
  620. sid = get16(&p, p_end);
  621. if (sid < 0)
  622. break;
  623. val = get8(&p, p_end);
  624. if (val < 0)
  625. break;
  626. desc_list_len = get16(&p, p_end) & 0xfff;
  627. if (desc_list_len < 0)
  628. break;
  629. desc_list_end = p + desc_list_len;
  630. if (desc_list_end > p_end)
  631. break;
  632. for(;;) {
  633. desc_tag = get8(&p, desc_list_end);
  634. if (desc_tag < 0)
  635. break;
  636. desc_len = get8(&p, desc_list_end);
  637. desc_end = p + desc_len;
  638. if (desc_end > desc_list_end)
  639. break;
  640. dprintf(ts->stream, "tag: 0x%02x len=%d\n",
  641. desc_tag, desc_len);
  642. switch(desc_tag) {
  643. case 0x48:
  644. service_type = get8(&p, p_end);
  645. if (service_type < 0)
  646. break;
  647. provider_name = getstr8(&p, p_end);
  648. if (!provider_name)
  649. break;
  650. name = getstr8(&p, p_end);
  651. if (name) {
  652. AVProgram *program = av_new_program(ts->stream, sid);
  653. if(program) {
  654. av_metadata_set(&program->metadata, "name", name);
  655. av_metadata_set(&program->metadata, "provider_name", provider_name);
  656. }
  657. }
  658. av_free(name);
  659. av_free(provider_name);
  660. break;
  661. default:
  662. break;
  663. }
  664. p = desc_end;
  665. }
  666. p = desc_list_end;
  667. }
  668. }
  669. static int64_t get_pts(const uint8_t *p)
  670. {
  671. int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
  672. pts |= (AV_RB16(p + 1) >> 1) << 15;
  673. pts |= AV_RB16(p + 3) >> 1;
  674. return pts;
  675. }
  676. static void new_pes_packet(PESContext *pes, AVPacket *pkt)
  677. {
  678. av_init_packet(pkt);
  679. pkt->destruct = av_destruct_packet;
  680. pkt->data = pes->buffer;
  681. pkt->size = pes->data_index;
  682. memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  683. pkt->stream_index = pes->st->index;
  684. pkt->pts = pes->pts;
  685. pkt->dts = pes->dts;
  686. /* store position of first TS packet of this PES packet */
  687. pkt->pos = pes->ts_packet_pos;
  688. /* reset pts values */
  689. pes->pts = AV_NOPTS_VALUE;
  690. pes->dts = AV_NOPTS_VALUE;
  691. pes->buffer = NULL;
  692. pes->data_index = 0;
  693. }
  694. /* return non zero if a packet could be constructed */
  695. static int mpegts_push_data(MpegTSFilter *filter,
  696. const uint8_t *buf, int buf_size, int is_start,
  697. int64_t pos)
  698. {
  699. PESContext *pes = filter->u.pes_filter.opaque;
  700. MpegTSContext *ts = pes->ts;
  701. const uint8_t *p;
  702. int len, code;
  703. if(!ts->pkt)
  704. return 0;
  705. if (is_start) {
  706. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  707. new_pes_packet(pes, ts->pkt);
  708. ts->stop_parse = 1;
  709. }
  710. pes->state = MPEGTS_HEADER;
  711. pes->data_index = 0;
  712. pes->ts_packet_pos = pos;
  713. }
  714. p = buf;
  715. while (buf_size > 0) {
  716. switch(pes->state) {
  717. case MPEGTS_HEADER:
  718. len = PES_START_SIZE - pes->data_index;
  719. if (len > buf_size)
  720. len = buf_size;
  721. memcpy(pes->header + pes->data_index, p, len);
  722. pes->data_index += len;
  723. p += len;
  724. buf_size -= len;
  725. if (pes->data_index == PES_START_SIZE) {
  726. /* we got all the PES or section header. We can now
  727. decide */
  728. #if 0
  729. av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
  730. #endif
  731. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  732. pes->header[2] == 0x01) {
  733. /* it must be an mpeg2 PES stream */
  734. code = pes->header[3] | 0x100;
  735. if (!pes->st || pes->st->discard == AVDISCARD_ALL ||
  736. !((code >= 0x1c0 && code <= 0x1df) ||
  737. (code >= 0x1e0 && code <= 0x1ef) ||
  738. (code == 0x1bd) || (code == 0x1fd)))
  739. goto skip;
  740. pes->state = MPEGTS_PESHEADER_FILL;
  741. pes->total_size = AV_RB16(pes->header + 4);
  742. /* NOTE: a zero total size means the PES size is
  743. unbounded */
  744. pes->pes_header_size = pes->header[8] + 9;
  745. } else {
  746. /* otherwise, it should be a table */
  747. /* skip packet */
  748. skip:
  749. pes->state = MPEGTS_SKIP;
  750. continue;
  751. }
  752. }
  753. break;
  754. /**********************************************/
  755. /* PES packing parsing */
  756. case MPEGTS_PESHEADER_FILL:
  757. len = pes->pes_header_size - pes->data_index;
  758. if (len < 0)
  759. return -1;
  760. if (len > buf_size)
  761. len = buf_size;
  762. memcpy(pes->header + pes->data_index, p, len);
  763. pes->data_index += len;
  764. p += len;
  765. buf_size -= len;
  766. if (pes->data_index == pes->pes_header_size) {
  767. const uint8_t *r;
  768. unsigned int flags;
  769. flags = pes->header[7];
  770. r = pes->header + 9;
  771. pes->pts = AV_NOPTS_VALUE;
  772. pes->dts = AV_NOPTS_VALUE;
  773. if ((flags & 0xc0) == 0x80) {
  774. pes->dts = pes->pts = get_pts(r);
  775. r += 5;
  776. } else if ((flags & 0xc0) == 0xc0) {
  777. pes->pts = get_pts(r);
  778. r += 5;
  779. pes->dts = get_pts(r);
  780. r += 5;
  781. }
  782. if (pes->total_size > pes->data_index - 6)
  783. pes->total_size -= pes->data_index - 6;
  784. else
  785. pes->total_size = MAX_PES_PAYLOAD;
  786. /* allocate pes buffer */
  787. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  788. if (!pes->buffer)
  789. return AVERROR(ENOMEM);
  790. /* we got the full header. We parse it and get the payload */
  791. pes->state = MPEGTS_PAYLOAD;
  792. pes->data_index = 0;
  793. }
  794. break;
  795. case MPEGTS_PAYLOAD:
  796. if (buf_size > 0) {
  797. if (pes->data_index+buf_size > pes->total_size) {
  798. new_pes_packet(pes, ts->pkt);
  799. pes->total_size = MAX_PES_PAYLOAD;
  800. pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
  801. if (!pes->buffer)
  802. return AVERROR(ENOMEM);
  803. ts->stop_parse = 1;
  804. }
  805. memcpy(pes->buffer+pes->data_index, p, buf_size);
  806. pes->data_index += buf_size;
  807. }
  808. buf_size = 0;
  809. break;
  810. case MPEGTS_SKIP:
  811. buf_size = 0;
  812. break;
  813. }
  814. }
  815. return 0;
  816. }
  817. typedef struct {
  818. uint32_t stream_type;
  819. enum CodecType codec_type;
  820. enum CodecID codec_id;
  821. } StreamType;
  822. static const StreamType ISO_types[] = {
  823. { 0x01, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  824. { 0x02, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
  825. { 0x03, CODEC_TYPE_AUDIO, CODEC_ID_MP3 },
  826. { 0x04, CODEC_TYPE_AUDIO, CODEC_ID_MP3 },
  827. { 0x0f, CODEC_TYPE_AUDIO, CODEC_ID_AAC },
  828. { 0x10, CODEC_TYPE_VIDEO, CODEC_ID_MPEG4 },
  829. { 0x1b, CODEC_TYPE_VIDEO, CODEC_ID_H264 },
  830. { 0xd1, CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
  831. { 0xea, CODEC_TYPE_VIDEO, CODEC_ID_VC1 },
  832. { 0 },
  833. };
  834. static const StreamType HDMV_types[] = {
  835. { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
  836. { 0x82, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
  837. { 0 },
  838. };
  839. /* ATSC ? */
  840. static const StreamType MISC_types[] = {
  841. { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
  842. { 0x8a, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
  843. {0x100, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, // demuxer internal
  844. { 0 },
  845. };
  846. static const StreamType REGD_types[] = {
  847. { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
  848. { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
  849. { 0 },
  850. };
  851. static void mpegts_find_stream_type(AVStream *st,
  852. uint32_t stream_type, const StreamType *types)
  853. {
  854. for (; types->stream_type; types++) {
  855. if (stream_type == types->stream_type) {
  856. st->codec->codec_type = types->codec_type;
  857. st->codec->codec_id = types->codec_id;
  858. return;
  859. }
  860. }
  861. }
  862. static AVStream *new_pes_av_stream(PESContext *pes, uint32_t code,
  863. uint32_t prog_reg_desc, uint32_t reg_desc)
  864. {
  865. AVStream *st = av_new_stream(pes->stream, pes->pid);
  866. if (!st)
  867. return NULL;
  868. av_set_pts_info(st, 33, 1, 90000);
  869. st->priv_data = pes;
  870. st->codec->codec_type = CODEC_TYPE_DATA;
  871. st->codec->codec_id = CODEC_ID_PROBE;
  872. st->need_parsing = AVSTREAM_PARSE_FULL;
  873. pes->st = st;
  874. dprintf(pes->stream, "stream_type=%x prog_reg_desc=%.4s reg_desc=%.4s\n",
  875. pes->stream_type, (char*)&prog_reg_desc, (char*)&reg_desc);
  876. if (pes->stream_type == 0x06) { // private data carrying pes data
  877. mpegts_find_stream_type(st, reg_desc, REGD_types);
  878. } else {
  879. mpegts_find_stream_type(st, pes->stream_type, ISO_types);
  880. if (prog_reg_desc == AV_RL32("HDMV") &&
  881. st->codec->codec_id == CODEC_ID_PROBE)
  882. mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
  883. if (st->codec->codec_id == CODEC_ID_PROBE)
  884. mpegts_find_stream_type(st, pes->stream_type, MISC_types);
  885. }
  886. return st;
  887. }
  888. static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
  889. {
  890. MpegTSFilter *tss;
  891. PESContext *pes;
  892. /* if no pid found, then add a pid context */
  893. pes = av_mallocz(sizeof(PESContext));
  894. if (!pes)
  895. return 0;
  896. pes->ts = ts;
  897. pes->stream = ts->stream;
  898. pes->pid = pid;
  899. pes->pcr_pid = pcr_pid;
  900. pes->stream_type = stream_type;
  901. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  902. if (!tss) {
  903. av_free(pes);
  904. return 0;
  905. }
  906. return pes;
  907. }
  908. /* handle one TS packet */
  909. static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
  910. {
  911. AVFormatContext *s = ts->stream;
  912. MpegTSFilter *tss;
  913. int len, pid, cc, cc_ok, afc, is_start;
  914. const uint8_t *p, *p_end;
  915. int64_t pos;
  916. pid = AV_RB16(packet + 1) & 0x1fff;
  917. if(pid && discard_pid(ts, pid))
  918. return 0;
  919. is_start = packet[1] & 0x40;
  920. tss = ts->pids[pid];
  921. if (ts->auto_guess && tss == NULL && is_start) {
  922. add_pes_stream(ts, pid, -1, 0);
  923. tss = ts->pids[pid];
  924. }
  925. if (!tss)
  926. return 0;
  927. /* continuity check (currently not used) */
  928. cc = (packet[3] & 0xf);
  929. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  930. tss->last_cc = cc;
  931. /* skip adaptation field */
  932. afc = (packet[3] >> 4) & 3;
  933. p = packet + 4;
  934. if (afc == 0) /* reserved value */
  935. return 0;
  936. if (afc == 2) /* adaptation field only */
  937. return 0;
  938. if (afc == 3) {
  939. /* skip adapation field */
  940. p += p[0] + 1;
  941. }
  942. /* if past the end of packet, ignore */
  943. p_end = packet + TS_PACKET_SIZE;
  944. if (p >= p_end)
  945. return 0;
  946. pos = url_ftell(ts->stream->pb);
  947. ts->pos47= pos % ts->raw_packet_size;
  948. if (tss->type == MPEGTS_SECTION) {
  949. if (is_start) {
  950. /* pointer field present */
  951. len = *p++;
  952. if (p + len > p_end)
  953. return 0;
  954. if (len && cc_ok) {
  955. /* write remaining section bytes */
  956. write_section_data(s, tss,
  957. p, len, 0);
  958. /* check whether filter has been closed */
  959. if (!ts->pids[pid])
  960. return 0;
  961. }
  962. p += len;
  963. if (p < p_end) {
  964. write_section_data(s, tss,
  965. p, p_end - p, 1);
  966. }
  967. } else {
  968. if (cc_ok) {
  969. write_section_data(s, tss,
  970. p, p_end - p, 0);
  971. }
  972. }
  973. } else {
  974. int ret;
  975. // Note: The position here points actually behind the current packet.
  976. if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
  977. pos - ts->raw_packet_size)) < 0)
  978. return ret;
  979. }
  980. return 0;
  981. }
  982. /* XXX: try to find a better synchro over several packets (use
  983. get_packet_size() ?) */
  984. static int mpegts_resync(ByteIOContext *pb)
  985. {
  986. int c, i;
  987. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  988. c = url_fgetc(pb);
  989. if (c < 0)
  990. return -1;
  991. if (c == 0x47) {
  992. url_fseek(pb, -1, SEEK_CUR);
  993. return 0;
  994. }
  995. }
  996. /* no sync found */
  997. return -1;
  998. }
  999. /* return -1 if error or EOF. Return 0 if OK. */
  1000. static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
  1001. {
  1002. int skip, len;
  1003. for(;;) {
  1004. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  1005. if (len != TS_PACKET_SIZE)
  1006. return AVERROR(EIO);
  1007. /* check paquet sync byte */
  1008. if (buf[0] != 0x47) {
  1009. /* find a new packet start */
  1010. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  1011. if (mpegts_resync(pb) < 0)
  1012. return AVERROR_INVALIDDATA;
  1013. else
  1014. continue;
  1015. } else {
  1016. skip = raw_packet_size - TS_PACKET_SIZE;
  1017. if (skip > 0)
  1018. url_fskip(pb, skip);
  1019. break;
  1020. }
  1021. }
  1022. return 0;
  1023. }
  1024. static int handle_packets(MpegTSContext *ts, int nb_packets)
  1025. {
  1026. AVFormatContext *s = ts->stream;
  1027. ByteIOContext *pb = s->pb;
  1028. uint8_t packet[TS_PACKET_SIZE];
  1029. int packet_num, ret;
  1030. ts->stop_parse = 0;
  1031. packet_num = 0;
  1032. for(;;) {
  1033. if (ts->stop_parse>0)
  1034. break;
  1035. packet_num++;
  1036. if (nb_packets != 0 && packet_num >= nb_packets)
  1037. break;
  1038. ret = read_packet(pb, packet, ts->raw_packet_size);
  1039. if (ret != 0)
  1040. return ret;
  1041. ret = handle_packet(ts, packet);
  1042. if (ret != 0)
  1043. return ret;
  1044. }
  1045. return 0;
  1046. }
  1047. static int mpegts_probe(AVProbeData *p)
  1048. {
  1049. #if 1
  1050. const int size= p->buf_size;
  1051. int score, fec_score, dvhs_score;
  1052. int check_count= size / TS_FEC_PACKET_SIZE;
  1053. #define CHECK_COUNT 10
  1054. if (check_count < CHECK_COUNT)
  1055. return -1;
  1056. score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1057. dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
  1058. fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
  1059. // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
  1060. // we need a clear definition for the returned score otherwise things will become messy sooner or later
  1061. if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
  1062. else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
  1063. else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
  1064. else return -1;
  1065. #else
  1066. /* only use the extension for safer guess */
  1067. if (match_ext(p->filename, "ts"))
  1068. return AVPROBE_SCORE_MAX;
  1069. else
  1070. return 0;
  1071. #endif
  1072. }
  1073. /* return the 90kHz PCR and the extension for the 27MHz PCR. return
  1074. (-1) if not available */
  1075. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  1076. const uint8_t *packet)
  1077. {
  1078. int afc, len, flags;
  1079. const uint8_t *p;
  1080. unsigned int v;
  1081. afc = (packet[3] >> 4) & 3;
  1082. if (afc <= 1)
  1083. return -1;
  1084. p = packet + 4;
  1085. len = p[0];
  1086. p++;
  1087. if (len == 0)
  1088. return -1;
  1089. flags = *p++;
  1090. len--;
  1091. if (!(flags & 0x10))
  1092. return -1;
  1093. if (len < 6)
  1094. return -1;
  1095. v = AV_RB32(p);
  1096. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  1097. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  1098. return 0;
  1099. }
  1100. static int mpegts_read_header(AVFormatContext *s,
  1101. AVFormatParameters *ap)
  1102. {
  1103. MpegTSContext *ts = s->priv_data;
  1104. ByteIOContext *pb = s->pb;
  1105. uint8_t buf[5*1024];
  1106. int len;
  1107. int64_t pos;
  1108. if (ap) {
  1109. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  1110. if(ap->mpeg2ts_raw){
  1111. av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
  1112. return -1;
  1113. }
  1114. }
  1115. /* read the first 1024 bytes to get packet size */
  1116. pos = url_ftell(pb);
  1117. len = get_buffer(pb, buf, sizeof(buf));
  1118. if (len != sizeof(buf))
  1119. goto fail;
  1120. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  1121. if (ts->raw_packet_size <= 0)
  1122. goto fail;
  1123. ts->stream = s;
  1124. ts->auto_guess = 0;
  1125. if (s->iformat == &mpegts_demuxer) {
  1126. /* normal demux */
  1127. /* first do a scaning to get all the services */
  1128. url_fseek(pb, pos, SEEK_SET);
  1129. mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
  1130. mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
  1131. handle_packets(ts, s->probesize);
  1132. /* if could not find service, enable auto_guess */
  1133. ts->auto_guess = 1;
  1134. dprintf(ts->stream, "tuning done\n");
  1135. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1136. } else {
  1137. AVStream *st;
  1138. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  1139. int64_t pcrs[2], pcr_h;
  1140. int packet_count[2];
  1141. uint8_t packet[TS_PACKET_SIZE];
  1142. /* only read packets */
  1143. st = av_new_stream(s, 0);
  1144. if (!st)
  1145. goto fail;
  1146. av_set_pts_info(st, 60, 1, 27000000);
  1147. st->codec->codec_type = CODEC_TYPE_DATA;
  1148. st->codec->codec_id = CODEC_ID_MPEG2TS;
  1149. /* we iterate until we find two PCRs to estimate the bitrate */
  1150. pcr_pid = -1;
  1151. nb_pcrs = 0;
  1152. nb_packets = 0;
  1153. for(;;) {
  1154. ret = read_packet(s->pb, packet, ts->raw_packet_size);
  1155. if (ret < 0)
  1156. return -1;
  1157. pid = AV_RB16(packet + 1) & 0x1fff;
  1158. if ((pcr_pid == -1 || pcr_pid == pid) &&
  1159. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  1160. pcr_pid = pid;
  1161. packet_count[nb_pcrs] = nb_packets;
  1162. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1163. nb_pcrs++;
  1164. if (nb_pcrs >= 2)
  1165. break;
  1166. }
  1167. nb_packets++;
  1168. }
  1169. /* NOTE1: the bitrate is computed without the FEC */
  1170. /* NOTE2: it is only the bitrate of the start of the stream */
  1171. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1172. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1173. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1174. st->codec->bit_rate = s->bit_rate;
  1175. st->start_time = ts->cur_pcr;
  1176. #if 0
  1177. av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
  1178. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1179. #endif
  1180. }
  1181. url_fseek(pb, pos, SEEK_SET);
  1182. return 0;
  1183. fail:
  1184. return -1;
  1185. }
  1186. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1187. static int mpegts_raw_read_packet(AVFormatContext *s,
  1188. AVPacket *pkt)
  1189. {
  1190. MpegTSContext *ts = s->priv_data;
  1191. int ret, i;
  1192. int64_t pcr_h, next_pcr_h, pos;
  1193. int pcr_l, next_pcr_l;
  1194. uint8_t pcr_buf[12];
  1195. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1196. return AVERROR(ENOMEM);
  1197. pkt->pos= url_ftell(s->pb);
  1198. ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
  1199. if (ret < 0) {
  1200. av_free_packet(pkt);
  1201. return ret;
  1202. }
  1203. if (ts->mpeg2ts_compute_pcr) {
  1204. /* compute exact PCR for each packet */
  1205. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1206. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1207. pos = url_ftell(s->pb);
  1208. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1209. url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1210. get_buffer(s->pb, pcr_buf, 12);
  1211. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1212. /* XXX: not precise enough */
  1213. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1214. (i + 1);
  1215. break;
  1216. }
  1217. }
  1218. url_fseek(s->pb, pos, SEEK_SET);
  1219. /* no next PCR found: we use previous increment */
  1220. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1221. }
  1222. pkt->pts = ts->cur_pcr;
  1223. pkt->duration = ts->pcr_incr;
  1224. ts->cur_pcr += ts->pcr_incr;
  1225. }
  1226. pkt->stream_index = 0;
  1227. return 0;
  1228. }
  1229. static int mpegts_read_packet(AVFormatContext *s,
  1230. AVPacket *pkt)
  1231. {
  1232. MpegTSContext *ts = s->priv_data;
  1233. int ret, i;
  1234. if (url_ftell(s->pb) != ts->last_pos) {
  1235. /* seek detected, flush pes buffer */
  1236. for (i = 0; i < NB_PID_MAX; i++) {
  1237. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1238. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1239. av_freep(&pes->buffer);
  1240. pes->data_index = 0;
  1241. pes->state = MPEGTS_SKIP; /* skip until pes header */
  1242. }
  1243. }
  1244. }
  1245. ts->pkt = pkt;
  1246. ret = handle_packets(ts, 0);
  1247. if (ret < 0) {
  1248. /* flush pes data left */
  1249. for (i = 0; i < NB_PID_MAX; i++) {
  1250. if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
  1251. PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
  1252. if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
  1253. new_pes_packet(pes, pkt);
  1254. ret = 0;
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. }
  1260. ts->last_pos = url_ftell(s->pb);
  1261. return ret;
  1262. }
  1263. static int mpegts_read_close(AVFormatContext *s)
  1264. {
  1265. MpegTSContext *ts = s->priv_data;
  1266. int i;
  1267. clear_programs(ts);
  1268. for(i=0;i<NB_PID_MAX;i++)
  1269. if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
  1270. return 0;
  1271. }
  1272. static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
  1273. int64_t *ppos, int64_t pos_limit)
  1274. {
  1275. MpegTSContext *ts = s->priv_data;
  1276. int64_t pos, timestamp;
  1277. uint8_t buf[TS_PACKET_SIZE];
  1278. int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
  1279. const int find_next= 1;
  1280. pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
  1281. if (find_next) {
  1282. for(;;) {
  1283. url_fseek(s->pb, pos, SEEK_SET);
  1284. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1285. return AV_NOPTS_VALUE;
  1286. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1287. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1288. break;
  1289. }
  1290. pos += ts->raw_packet_size;
  1291. }
  1292. } else {
  1293. for(;;) {
  1294. pos -= ts->raw_packet_size;
  1295. if (pos < 0)
  1296. return AV_NOPTS_VALUE;
  1297. url_fseek(s->pb, pos, SEEK_SET);
  1298. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1299. return AV_NOPTS_VALUE;
  1300. if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
  1301. parse_pcr(&timestamp, &pcr_l, buf) == 0) {
  1302. break;
  1303. }
  1304. }
  1305. }
  1306. *ppos = pos;
  1307. return timestamp;
  1308. }
  1309. static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1310. MpegTSContext *ts = s->priv_data;
  1311. uint8_t buf[TS_PACKET_SIZE];
  1312. int64_t pos;
  1313. if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
  1314. return -1;
  1315. pos= url_ftell(s->pb);
  1316. for(;;) {
  1317. url_fseek(s->pb, pos, SEEK_SET);
  1318. if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
  1319. return -1;
  1320. // pid = AV_RB16(buf + 1) & 0x1fff;
  1321. if(buf[1] & 0x40) break;
  1322. pos += ts->raw_packet_size;
  1323. }
  1324. url_fseek(s->pb, pos, SEEK_SET);
  1325. return 0;
  1326. }
  1327. /**************************************************************/
  1328. /* parsing functions - called from other demuxers such as RTP */
  1329. MpegTSContext *mpegts_parse_open(AVFormatContext *s)
  1330. {
  1331. MpegTSContext *ts;
  1332. ts = av_mallocz(sizeof(MpegTSContext));
  1333. if (!ts)
  1334. return NULL;
  1335. /* no stream case, currently used by RTP */
  1336. ts->raw_packet_size = TS_PACKET_SIZE;
  1337. ts->stream = s;
  1338. ts->auto_guess = 1;
  1339. return ts;
  1340. }
  1341. /* return the consumed length if a packet was output, or -1 if no
  1342. packet is output */
  1343. int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1344. const uint8_t *buf, int len)
  1345. {
  1346. int len1;
  1347. len1 = len;
  1348. ts->pkt = pkt;
  1349. ts->stop_parse = 0;
  1350. for(;;) {
  1351. if (ts->stop_parse>0)
  1352. break;
  1353. if (len < TS_PACKET_SIZE)
  1354. return -1;
  1355. if (buf[0] != 0x47) {
  1356. buf++;
  1357. len--;
  1358. } else {
  1359. handle_packet(ts, buf);
  1360. buf += TS_PACKET_SIZE;
  1361. len -= TS_PACKET_SIZE;
  1362. }
  1363. }
  1364. return len1 - len;
  1365. }
  1366. void mpegts_parse_close(MpegTSContext *ts)
  1367. {
  1368. int i;
  1369. for(i=0;i<NB_PID_MAX;i++)
  1370. av_free(ts->pids[i]);
  1371. av_free(ts);
  1372. }
  1373. AVInputFormat mpegts_demuxer = {
  1374. "mpegts",
  1375. NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
  1376. sizeof(MpegTSContext),
  1377. mpegts_probe,
  1378. mpegts_read_header,
  1379. mpegts_read_packet,
  1380. mpegts_read_close,
  1381. read_seek,
  1382. mpegts_get_pcr,
  1383. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1384. };
  1385. AVInputFormat mpegtsraw_demuxer = {
  1386. "mpegtsraw",
  1387. NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
  1388. sizeof(MpegTSContext),
  1389. NULL,
  1390. mpegts_read_header,
  1391. mpegts_raw_read_packet,
  1392. mpegts_read_close,
  1393. read_seek,
  1394. mpegts_get_pcr,
  1395. .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
  1396. };