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.

1279 lines
35KB

  1. /*
  2. * MPEG2 transport stream (aka DVB) demux
  3. * Copyright (c) 2002-2003 Fabrice Bellard.
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #include "avformat.h"
  20. #include "mpegts.h"
  21. //#define DEBUG_SI
  22. /* 1.0 second at 24Mbit/s */
  23. #define MAX_SCAN_PACKETS 32000
  24. /* maximum size in which we look for synchronisation if
  25. synchronisation is lost */
  26. #define MAX_RESYNC_SIZE 4096
  27. static int add_pes_stream(MpegTSContext *ts, int pid);
  28. enum MpegTSFilterType {
  29. MPEGTS_PES,
  30. MPEGTS_SECTION,
  31. };
  32. typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
  33. typedef struct MpegTSPESFilter {
  34. PESCallback *pes_cb;
  35. void *opaque;
  36. } MpegTSPESFilter;
  37. typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
  38. typedef void SetServiceCallback(void *opaque, int ret);
  39. typedef struct MpegTSSectionFilter {
  40. int section_index;
  41. int section_h_size;
  42. uint8_t *section_buf;
  43. int check_crc:1;
  44. int end_of_section_reached:1;
  45. SectionCallback *section_cb;
  46. void *opaque;
  47. } MpegTSSectionFilter;
  48. typedef struct MpegTSFilter {
  49. int pid;
  50. int last_cc; /* last cc code (-1 if first packet) */
  51. enum MpegTSFilterType type;
  52. union {
  53. MpegTSPESFilter pes_filter;
  54. MpegTSSectionFilter section_filter;
  55. } u;
  56. } MpegTSFilter;
  57. typedef struct MpegTSService {
  58. int running:1;
  59. int sid;
  60. char *provider_name;
  61. char *name;
  62. } MpegTSService;
  63. struct MpegTSContext {
  64. /* user data */
  65. AVFormatContext *stream;
  66. int raw_packet_size; /* raw packet size, including FEC if present */
  67. int auto_guess; /* if true, all pids are analized to find streams */
  68. int set_service_ret;
  69. int mpeg2ts_raw; /* force raw MPEG2 transport stream output, if possible */
  70. int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
  71. /* used to estimate the exact PCR */
  72. int64_t cur_pcr;
  73. int pcr_incr;
  74. /* data needed to handle file based ts */
  75. int stop_parse; /* stop parsing loop */
  76. AVPacket *pkt; /* packet containing av data */
  77. /******************************************/
  78. /* private mpegts data */
  79. /* scan context */
  80. MpegTSFilter *sdt_filter;
  81. int nb_services;
  82. MpegTSService **services;
  83. /* set service context (XXX: allocated it ?) */
  84. SetServiceCallback *set_service_cb;
  85. void *set_service_opaque;
  86. MpegTSFilter *pat_filter;
  87. MpegTSFilter *pmt_filter;
  88. int req_sid;
  89. MpegTSFilter *pids[NB_PID_MAX];
  90. };
  91. static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
  92. const uint8_t *buf, int buf_size, int is_start)
  93. {
  94. MpegTSSectionFilter *tss = &tss1->u.section_filter;
  95. int len;
  96. unsigned int crc;
  97. if (is_start) {
  98. memcpy(tss->section_buf, buf, buf_size);
  99. tss->section_index = buf_size;
  100. tss->section_h_size = -1;
  101. tss->end_of_section_reached = 0;
  102. } else {
  103. if (tss->end_of_section_reached)
  104. return;
  105. len = 4096 - tss->section_index;
  106. if (buf_size < len)
  107. len = buf_size;
  108. memcpy(tss->section_buf + tss->section_index, buf, len);
  109. tss->section_index += len;
  110. }
  111. /* compute section length if possible */
  112. if (tss->section_h_size == -1 && tss->section_index >= 3) {
  113. len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
  114. if (len > 4096)
  115. return;
  116. tss->section_h_size = len;
  117. }
  118. if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
  119. if (tss->check_crc) {
  120. crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
  121. if (crc != 0)
  122. goto invalid_crc;
  123. }
  124. tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
  125. invalid_crc:
  126. tss->end_of_section_reached = 1;
  127. }
  128. }
  129. MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
  130. SectionCallback *section_cb, void *opaque,
  131. int check_crc)
  132. {
  133. MpegTSFilter *filter;
  134. MpegTSSectionFilter *sec;
  135. #ifdef DEBUG_SI
  136. printf("Filter: pid=0x%x\n", pid);
  137. #endif
  138. if (pid >= NB_PID_MAX || ts->pids[pid])
  139. return NULL;
  140. filter = av_mallocz(sizeof(MpegTSFilter));
  141. if (!filter)
  142. return NULL;
  143. ts->pids[pid] = filter;
  144. filter->type = MPEGTS_SECTION;
  145. filter->pid = pid;
  146. filter->last_cc = -1;
  147. sec = &filter->u.section_filter;
  148. sec->section_cb = section_cb;
  149. sec->opaque = opaque;
  150. sec->section_buf = av_malloc(MAX_SECTION_SIZE);
  151. sec->check_crc = check_crc;
  152. if (!sec->section_buf) {
  153. av_free(filter);
  154. return NULL;
  155. }
  156. return filter;
  157. }
  158. MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
  159. PESCallback *pes_cb,
  160. void *opaque)
  161. {
  162. MpegTSFilter *filter;
  163. MpegTSPESFilter *pes;
  164. if (pid >= NB_PID_MAX || ts->pids[pid])
  165. return NULL;
  166. filter = av_mallocz(sizeof(MpegTSFilter));
  167. if (!filter)
  168. return NULL;
  169. ts->pids[pid] = filter;
  170. filter->type = MPEGTS_PES;
  171. filter->pid = pid;
  172. filter->last_cc = -1;
  173. pes = &filter->u.pes_filter;
  174. pes->pes_cb = pes_cb;
  175. pes->opaque = opaque;
  176. return filter;
  177. }
  178. void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
  179. {
  180. int pid;
  181. pid = filter->pid;
  182. if (filter->type == MPEGTS_SECTION)
  183. av_freep(&filter->u.section_filter.section_buf);
  184. av_free(filter);
  185. ts->pids[pid] = NULL;
  186. }
  187. /* autodetect fec presence. Must have at least 1024 bytes */
  188. static int get_packet_size(const uint8_t *buf, int size)
  189. {
  190. int i;
  191. if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
  192. return -1;
  193. for(i=0;i<5;i++) {
  194. if (buf[i * TS_PACKET_SIZE] != 0x47)
  195. goto try_fec;
  196. }
  197. return TS_PACKET_SIZE;
  198. try_fec:
  199. for(i=0;i<5;i++) {
  200. if (buf[i * TS_FEC_PACKET_SIZE] != 0x47)
  201. return -1;
  202. }
  203. return TS_FEC_PACKET_SIZE;
  204. }
  205. typedef struct SectionHeader {
  206. uint8_t tid;
  207. uint16_t id;
  208. uint8_t version;
  209. uint8_t sec_num;
  210. uint8_t last_sec_num;
  211. } SectionHeader;
  212. static inline int get8(const uint8_t **pp, const uint8_t *p_end)
  213. {
  214. const uint8_t *p;
  215. int c;
  216. p = *pp;
  217. if (p >= p_end)
  218. return -1;
  219. c = *p++;
  220. *pp = p;
  221. return c;
  222. }
  223. static inline int get16(const uint8_t **pp, const uint8_t *p_end)
  224. {
  225. const uint8_t *p;
  226. int c;
  227. p = *pp;
  228. if ((p + 1) >= p_end)
  229. return -1;
  230. c = (p[0] << 8) | p[1];
  231. p += 2;
  232. *pp = p;
  233. return c;
  234. }
  235. /* read and allocate a DVB string preceeded by its length */
  236. static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
  237. {
  238. int len;
  239. const uint8_t *p;
  240. char *str;
  241. p = *pp;
  242. len = get8(&p, p_end);
  243. if (len < 0)
  244. return NULL;
  245. if ((p + len) > p_end)
  246. return NULL;
  247. str = av_malloc(len + 1);
  248. if (!str)
  249. return NULL;
  250. memcpy(str, p, len);
  251. str[len] = '\0';
  252. p += len;
  253. *pp = p;
  254. return str;
  255. }
  256. static int parse_section_header(SectionHeader *h,
  257. const uint8_t **pp, const uint8_t *p_end)
  258. {
  259. int val;
  260. val = get8(pp, p_end);
  261. if (val < 0)
  262. return -1;
  263. h->tid = val;
  264. *pp += 2;
  265. val = get16(pp, p_end);
  266. if (val < 0)
  267. return -1;
  268. h->id = val;
  269. val = get8(pp, p_end);
  270. if (val < 0)
  271. return -1;
  272. h->version = (val >> 1) & 0x1f;
  273. val = get8(pp, p_end);
  274. if (val < 0)
  275. return -1;
  276. h->sec_num = val;
  277. val = get8(pp, p_end);
  278. if (val < 0)
  279. return -1;
  280. h->last_sec_num = val;
  281. return 0;
  282. }
  283. static MpegTSService *new_service(MpegTSContext *ts, int sid,
  284. char *provider_name, char *name)
  285. {
  286. MpegTSService *service;
  287. #ifdef DEBUG_SI
  288. printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
  289. sid, provider_name, name);
  290. #endif
  291. service = av_mallocz(sizeof(MpegTSService));
  292. if (!service)
  293. return NULL;
  294. service->sid = sid;
  295. service->provider_name = provider_name;
  296. service->name = name;
  297. dynarray_add(&ts->services, &ts->nb_services, service);
  298. return service;
  299. }
  300. static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
  301. {
  302. MpegTSContext *ts = opaque;
  303. SectionHeader h1, *h = &h1;
  304. const uint8_t *p, *p_end;
  305. int program_info_length, pcr_pid, pid, stream_type, desc_length;
  306. #ifdef DEBUG_SI
  307. printf("PMT:\n");
  308. av_hex_dump((uint8_t *)section, section_len);
  309. #endif
  310. p_end = section + section_len - 4;
  311. p = section;
  312. if (parse_section_header(h, &p, p_end) < 0)
  313. return;
  314. #ifdef DEBUG_SI
  315. printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
  316. #endif
  317. if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
  318. return;
  319. pcr_pid = get16(&p, p_end) & 0x1fff;
  320. if (pcr_pid < 0)
  321. return;
  322. #ifdef DEBUG_SI
  323. printf("pcr_pid=0x%x\n", pcr_pid);
  324. #endif
  325. program_info_length = get16(&p, p_end) & 0xfff;
  326. if (program_info_length < 0)
  327. return;
  328. p += program_info_length;
  329. if (p >= p_end)
  330. return;
  331. for(;;) {
  332. stream_type = get8(&p, p_end);
  333. if (stream_type < 0)
  334. break;
  335. pid = get16(&p, p_end) & 0x1fff;
  336. if (pid < 0)
  337. break;
  338. desc_length = get16(&p, p_end) & 0xfff;
  339. if (desc_length < 0)
  340. break;
  341. p += desc_length;
  342. if (p > p_end)
  343. return;
  344. #ifdef DEBUG_SI
  345. printf("stream_type=%d pid=0x%x\n", stream_type, pid);
  346. #endif
  347. /* now create ffmpeg stream */
  348. switch(stream_type) {
  349. case STREAM_TYPE_AUDIO_MPEG1:
  350. case STREAM_TYPE_AUDIO_MPEG2:
  351. case STREAM_TYPE_VIDEO_MPEG1:
  352. case STREAM_TYPE_VIDEO_MPEG2:
  353. case STREAM_TYPE_AUDIO_AC3:
  354. add_pes_stream(ts, pid);
  355. break;
  356. default:
  357. /* we ignore the other streams */
  358. break;
  359. }
  360. }
  361. /* all parameters are there */
  362. ts->set_service_cb(ts->set_service_opaque, 0);
  363. mpegts_close_filter(ts, ts->pmt_filter);
  364. ts->pmt_filter = NULL;
  365. }
  366. static void pat_cb(void *opaque, const uint8_t *section, int section_len)
  367. {
  368. MpegTSContext *ts = opaque;
  369. SectionHeader h1, *h = &h1;
  370. const uint8_t *p, *p_end;
  371. int sid, pmt_pid;
  372. #ifdef DEBUG_SI
  373. printf("PAT:\n");
  374. av_hex_dump((uint8_t *)section, section_len);
  375. #endif
  376. p_end = section + section_len - 4;
  377. p = section;
  378. if (parse_section_header(h, &p, p_end) < 0)
  379. return;
  380. if (h->tid != PAT_TID)
  381. return;
  382. for(;;) {
  383. sid = get16(&p, p_end);
  384. if (sid < 0)
  385. break;
  386. pmt_pid = get16(&p, p_end) & 0x1fff;
  387. if (pmt_pid < 0)
  388. break;
  389. #ifdef DEBUG_SI
  390. printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
  391. #endif
  392. if (sid == 0x0000) {
  393. /* NIT info */
  394. } else {
  395. if (ts->req_sid == sid) {
  396. ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
  397. pmt_cb, ts, 1);
  398. goto found;
  399. }
  400. }
  401. }
  402. /* not found */
  403. ts->set_service_cb(ts->set_service_opaque, -1);
  404. found:
  405. mpegts_close_filter(ts, ts->pat_filter);
  406. ts->pat_filter = NULL;
  407. }
  408. /* add all services found in the PAT */
  409. static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
  410. {
  411. MpegTSContext *ts = opaque;
  412. SectionHeader h1, *h = &h1;
  413. const uint8_t *p, *p_end;
  414. int sid, pmt_pid;
  415. char *provider_name, *name;
  416. char buf[256];
  417. #ifdef DEBUG_SI
  418. printf("PAT:\n");
  419. av_hex_dump((uint8_t *)section, section_len);
  420. #endif
  421. p_end = section + section_len - 4;
  422. p = section;
  423. if (parse_section_header(h, &p, p_end) < 0)
  424. return;
  425. if (h->tid != PAT_TID)
  426. return;
  427. for(;;) {
  428. sid = get16(&p, p_end);
  429. if (sid < 0)
  430. break;
  431. pmt_pid = get16(&p, p_end) & 0x1fff;
  432. if (pmt_pid < 0)
  433. break;
  434. #ifdef DEBUG_SI
  435. printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
  436. #endif
  437. if (sid == 0x0000) {
  438. /* NIT info */
  439. } else {
  440. /* add the service with a dummy name */
  441. snprintf(buf, sizeof(buf), "Service %x\n", sid);
  442. name = av_strdup(buf);
  443. provider_name = av_strdup("");
  444. if (name && provider_name) {
  445. new_service(ts, sid, provider_name, name);
  446. } else {
  447. av_freep(&name);
  448. av_freep(&provider_name);
  449. }
  450. }
  451. }
  452. ts->stop_parse = 1;
  453. /* remove filter */
  454. mpegts_close_filter(ts, ts->pat_filter);
  455. ts->pat_filter = NULL;
  456. }
  457. void mpegts_set_service(MpegTSContext *ts, int sid,
  458. SetServiceCallback *set_service_cb, void *opaque)
  459. {
  460. ts->set_service_cb = set_service_cb;
  461. ts->set_service_opaque = opaque;
  462. ts->req_sid = sid;
  463. ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
  464. pat_cb, ts, 1);
  465. }
  466. static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
  467. {
  468. MpegTSContext *ts = opaque;
  469. SectionHeader h1, *h = &h1;
  470. const uint8_t *p, *p_end, *desc_list_end, *desc_end;
  471. int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
  472. char *name, *provider_name;
  473. #ifdef DEBUG_SI
  474. printf("SDT:\n");
  475. av_hex_dump((uint8_t *)section, section_len);
  476. #endif
  477. p_end = section + section_len - 4;
  478. p = section;
  479. if (parse_section_header(h, &p, p_end) < 0)
  480. return;
  481. if (h->tid != SDT_TID)
  482. return;
  483. onid = get16(&p, p_end);
  484. if (onid < 0)
  485. return;
  486. val = get8(&p, p_end);
  487. if (val < 0)
  488. return;
  489. for(;;) {
  490. sid = get16(&p, p_end);
  491. if (sid < 0)
  492. break;
  493. val = get8(&p, p_end);
  494. if (val < 0)
  495. break;
  496. desc_list_len = get16(&p, p_end) & 0xfff;
  497. if (desc_list_len < 0)
  498. break;
  499. desc_list_end = p + desc_list_len;
  500. if (desc_list_end > p_end)
  501. break;
  502. for(;;) {
  503. desc_tag = get8(&p, desc_list_end);
  504. if (desc_tag < 0)
  505. break;
  506. desc_len = get8(&p, desc_list_end);
  507. desc_end = p + desc_len;
  508. if (desc_end > desc_list_end)
  509. break;
  510. #ifdef DEBUG_SI
  511. printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
  512. #endif
  513. switch(desc_tag) {
  514. case 0x48:
  515. service_type = get8(&p, p_end);
  516. if (service_type < 0)
  517. break;
  518. provider_name = getstr8(&p, p_end);
  519. if (!provider_name)
  520. break;
  521. name = getstr8(&p, p_end);
  522. if (!name)
  523. break;
  524. new_service(ts, sid, provider_name, name);
  525. break;
  526. default:
  527. break;
  528. }
  529. p = desc_end;
  530. }
  531. p = desc_list_end;
  532. }
  533. ts->stop_parse = 1;
  534. /* remove filter */
  535. mpegts_close_filter(ts, ts->sdt_filter);
  536. ts->sdt_filter = NULL;
  537. }
  538. /* scan services in a transport stream by looking at the SDT */
  539. void mpegts_scan_sdt(MpegTSContext *ts)
  540. {
  541. ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
  542. sdt_cb, ts, 1);
  543. }
  544. /* scan services in a transport stream by looking at the PAT (better
  545. than nothing !) */
  546. void mpegts_scan_pat(MpegTSContext *ts)
  547. {
  548. ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
  549. pat_scan_cb, ts, 1);
  550. }
  551. /* TS stream handling */
  552. enum MpegTSState {
  553. MPEGTS_HEADER = 0,
  554. MPEGTS_PESHEADER_FILL,
  555. MPEGTS_PAYLOAD,
  556. MPEGTS_SKIP,
  557. };
  558. /* enough for PES header + length */
  559. #define PES_START_SIZE 9
  560. #define MAX_PES_HEADER_SIZE (9 + 255)
  561. typedef struct PESContext {
  562. int pid;
  563. MpegTSContext *ts;
  564. AVFormatContext *stream;
  565. AVStream *st;
  566. enum MpegTSState state;
  567. /* used to get the format */
  568. int data_index;
  569. int total_size;
  570. int pes_header_size;
  571. int64_t pts, dts;
  572. uint8_t header[MAX_PES_HEADER_SIZE];
  573. } PESContext;
  574. static int64_t get_pts(const uint8_t *p)
  575. {
  576. int64_t pts;
  577. int val;
  578. pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
  579. val = (p[1] << 8) | p[2];
  580. pts |= (int64_t)(val >> 1) << 15;
  581. val = (p[3] << 8) | p[4];
  582. pts |= (int64_t)(val >> 1);
  583. return pts;
  584. }
  585. /* return non zero if a packet could be constructed */
  586. static void mpegts_push_data(void *opaque,
  587. const uint8_t *buf, int buf_size, int is_start)
  588. {
  589. PESContext *pes = opaque;
  590. MpegTSContext *ts = pes->ts;
  591. AVStream *st;
  592. const uint8_t *p;
  593. int len, code, codec_type, codec_id;
  594. if (is_start) {
  595. pes->state = MPEGTS_HEADER;
  596. pes->data_index = 0;
  597. }
  598. p = buf;
  599. while (buf_size > 0) {
  600. switch(pes->state) {
  601. case MPEGTS_HEADER:
  602. len = PES_START_SIZE - pes->data_index;
  603. if (len > buf_size)
  604. len = buf_size;
  605. memcpy(pes->header + pes->data_index, p, len);
  606. pes->data_index += len;
  607. p += len;
  608. buf_size -= len;
  609. if (pes->data_index == PES_START_SIZE) {
  610. /* we got all the PES or section header. We can now
  611. decide */
  612. #if 0
  613. av_hex_dump(pes->header, pes->data_index);
  614. #endif
  615. if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
  616. pes->header[2] == 0x01) {
  617. /* it must be an mpeg2 PES stream */
  618. code = pes->header[3] | 0x100;
  619. if (!((code >= 0x1c0 && code <= 0x1df) ||
  620. (code >= 0x1e0 && code <= 0x1ef) ||
  621. (code == 0x1bd)))
  622. goto skip;
  623. if (!pes->st) {
  624. /* allocate stream */
  625. if (code >= 0x1c0 && code <= 0x1df) {
  626. codec_type = CODEC_TYPE_AUDIO;
  627. codec_id = CODEC_ID_MP2;
  628. } else if (code == 0x1bd) {
  629. codec_type = CODEC_TYPE_AUDIO;
  630. codec_id = CODEC_ID_AC3;
  631. } else {
  632. codec_type = CODEC_TYPE_VIDEO;
  633. codec_id = CODEC_ID_MPEG1VIDEO;
  634. }
  635. st = av_new_stream(pes->stream, pes->pid);
  636. if (st) {
  637. st->priv_data = pes;
  638. st->codec.codec_type = codec_type;
  639. st->codec.codec_id = codec_id;
  640. pes->st = st;
  641. }
  642. }
  643. pes->state = MPEGTS_PESHEADER_FILL;
  644. pes->total_size = (pes->header[4] << 8) | pes->header[5];
  645. /* NOTE: a zero total size means the PES size is
  646. unbounded */
  647. if (pes->total_size)
  648. pes->total_size += 6;
  649. pes->pes_header_size = pes->header[8] + 9;
  650. } else {
  651. /* otherwise, it should be a table */
  652. /* skip packet */
  653. skip:
  654. pes->state = MPEGTS_SKIP;
  655. continue;
  656. }
  657. }
  658. break;
  659. /**********************************************/
  660. /* PES packing parsing */
  661. case MPEGTS_PESHEADER_FILL:
  662. len = pes->pes_header_size - pes->data_index;
  663. if (len > buf_size)
  664. len = buf_size;
  665. memcpy(pes->header + pes->data_index, p, len);
  666. pes->data_index += len;
  667. p += len;
  668. buf_size -= len;
  669. if (pes->data_index == pes->pes_header_size) {
  670. const uint8_t *r;
  671. unsigned int flags;
  672. flags = pes->header[7];
  673. r = pes->header + 9;
  674. pes->pts = AV_NOPTS_VALUE;
  675. pes->dts = AV_NOPTS_VALUE;
  676. if ((flags & 0xc0) == 0x80) {
  677. pes->pts = get_pts(r);
  678. r += 5;
  679. } else if ((flags & 0xc0) == 0xc0) {
  680. pes->pts = get_pts(r);
  681. r += 5;
  682. pes->dts = get_pts(r);
  683. r += 5;
  684. }
  685. /* we got the full header. We parse it and get the payload */
  686. pes->state = MPEGTS_PAYLOAD;
  687. }
  688. break;
  689. case MPEGTS_PAYLOAD:
  690. if (pes->total_size) {
  691. len = pes->total_size - pes->data_index;
  692. if (len > buf_size)
  693. len = buf_size;
  694. } else {
  695. len = buf_size;
  696. }
  697. if (len > 0) {
  698. AVPacket *pkt = ts->pkt;
  699. if (pes->st && av_new_packet(pkt, len) == 0) {
  700. memcpy(pkt->data, p, len);
  701. pkt->stream_index = pes->st->index;
  702. pkt->pts = pes->pts;
  703. /* reset pts values */
  704. pes->pts = AV_NOPTS_VALUE;
  705. pes->dts = AV_NOPTS_VALUE;
  706. ts->stop_parse = 1;
  707. return;
  708. }
  709. }
  710. buf_size = 0;
  711. break;
  712. case MPEGTS_SKIP:
  713. buf_size = 0;
  714. break;
  715. }
  716. }
  717. }
  718. static int add_pes_stream(MpegTSContext *ts, int pid)
  719. {
  720. MpegTSFilter *tss;
  721. PESContext *pes;
  722. /* if no pid found, then add a pid context */
  723. pes = av_mallocz(sizeof(PESContext));
  724. if (!pes)
  725. return -1;
  726. pes->ts = ts;
  727. pes->stream = ts->stream;
  728. pes->pid = pid;
  729. tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
  730. if (!tss) {
  731. av_free(pes);
  732. return -1;
  733. }
  734. return 0;
  735. }
  736. /* handle one TS packet */
  737. static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
  738. {
  739. AVFormatContext *s = ts->stream;
  740. MpegTSFilter *tss;
  741. int len, pid, cc, cc_ok, afc, is_start;
  742. const uint8_t *p, *p_end;
  743. pid = ((packet[1] & 0x1f) << 8) | packet[2];
  744. is_start = packet[1] & 0x40;
  745. tss = ts->pids[pid];
  746. if (ts->auto_guess && tss == NULL && is_start) {
  747. add_pes_stream(ts, pid);
  748. tss = ts->pids[pid];
  749. }
  750. if (!tss)
  751. return;
  752. /* continuity check (currently not used) */
  753. cc = (packet[3] & 0xf);
  754. cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
  755. tss->last_cc = cc;
  756. /* skip adaptation field */
  757. afc = (packet[3] >> 4) & 3;
  758. p = packet + 4;
  759. if (afc == 0) /* reserved value */
  760. return;
  761. if (afc == 2) /* adaptation field only */
  762. return;
  763. if (afc == 3) {
  764. /* skip adapation field */
  765. p += p[0] + 1;
  766. }
  767. /* if past the end of packet, ignore */
  768. p_end = packet + TS_PACKET_SIZE;
  769. if (p >= p_end)
  770. return;
  771. if (tss->type == MPEGTS_SECTION) {
  772. if (is_start) {
  773. /* pointer field present */
  774. len = *p++;
  775. if (p + len > p_end)
  776. return;
  777. if (len && cc_ok) {
  778. /* write remaning section bytes */
  779. write_section_data(s, tss,
  780. p, len, 0);
  781. }
  782. p += len;
  783. if (p < p_end) {
  784. write_section_data(s, tss,
  785. p, p_end - p, 1);
  786. }
  787. } else {
  788. if (cc_ok) {
  789. write_section_data(s, tss,
  790. p, p_end - p, 0);
  791. }
  792. }
  793. } else {
  794. tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
  795. p, p_end - p, is_start);
  796. }
  797. }
  798. /* XXX: try to find a better synchro over several packets (use
  799. get_packet_size() ?) */
  800. static int mpegts_resync(ByteIOContext *pb)
  801. {
  802. int c, i;
  803. for(i = 0;i < MAX_RESYNC_SIZE; i++) {
  804. c = url_fgetc(pb);
  805. if (c < 0)
  806. return -1;
  807. if (c == 0x47) {
  808. url_fseek(pb, -1, SEEK_CUR);
  809. return 0;
  810. }
  811. }
  812. /* no sync found */
  813. return -1;
  814. }
  815. /* return -1 if error or EOF. Return 0 if OK. */
  816. static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
  817. {
  818. int skip, len;
  819. for(;;) {
  820. len = get_buffer(pb, buf, TS_PACKET_SIZE);
  821. if (len != TS_PACKET_SIZE)
  822. return AVERROR_IO;
  823. /* check paquet sync byte */
  824. if (buf[0] != 0x47) {
  825. /* find a new packet start */
  826. url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
  827. if (mpegts_resync(pb) < 0)
  828. return AVERROR_INVALIDDATA;
  829. else
  830. continue;
  831. } else {
  832. skip = raw_packet_size - TS_PACKET_SIZE;
  833. if (skip > 0)
  834. url_fskip(pb, skip);
  835. break;
  836. }
  837. }
  838. return 0;
  839. }
  840. static int handle_packets(MpegTSContext *ts, int nb_packets)
  841. {
  842. AVFormatContext *s = ts->stream;
  843. ByteIOContext *pb = &s->pb;
  844. uint8_t packet[TS_PACKET_SIZE];
  845. int packet_num, ret;
  846. ts->stop_parse = 0;
  847. packet_num = 0;
  848. for(;;) {
  849. if (ts->stop_parse)
  850. break;
  851. packet_num++;
  852. if (nb_packets != 0 && packet_num >= nb_packets)
  853. break;
  854. ret = read_packet(pb, packet, ts->raw_packet_size);
  855. if (ret != 0)
  856. return ret;
  857. handle_packet(ts, packet);
  858. }
  859. return 0;
  860. }
  861. static int mpegts_probe(AVProbeData *p)
  862. {
  863. #if 1
  864. int size;
  865. size = get_packet_size(p->buf, p->buf_size);
  866. if (size < 0)
  867. return 0;
  868. return AVPROBE_SCORE_MAX - 1;
  869. #else
  870. /* only use the extension for safer guess */
  871. if (match_ext(p->filename, "ts"))
  872. return AVPROBE_SCORE_MAX;
  873. else
  874. return 0;
  875. #endif
  876. }
  877. void set_service_cb(void *opaque, int ret)
  878. {
  879. MpegTSContext *ts = opaque;
  880. ts->set_service_ret = ret;
  881. ts->stop_parse = 1;
  882. }
  883. /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
  884. (-1) if not available */
  885. static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
  886. const uint8_t *packet)
  887. {
  888. int afc, len, flags;
  889. const uint8_t *p;
  890. unsigned int v;
  891. afc = (packet[3] >> 4) & 3;
  892. if (afc <= 1)
  893. return -1;
  894. p = packet + 4;
  895. len = p[0];
  896. p++;
  897. if (len == 0)
  898. return -1;
  899. flags = *p++;
  900. len--;
  901. if (!(flags & 0x10))
  902. return -1;
  903. if (len < 6)
  904. return -1;
  905. v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
  906. *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
  907. *ppcr_low = ((p[4] & 1) << 8) | p[5];
  908. return 0;
  909. }
  910. static int mpegts_read_header(AVFormatContext *s,
  911. AVFormatParameters *ap)
  912. {
  913. MpegTSContext *ts = s->priv_data;
  914. ByteIOContext *pb = &s->pb;
  915. uint8_t buf[1024];
  916. int len, sid;
  917. int64_t pos;
  918. MpegTSService *service;
  919. if (ap) {
  920. ts->mpeg2ts_raw = ap->mpeg2ts_raw;
  921. ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
  922. }
  923. /* read the first 1024 bytes to get packet size */
  924. pos = url_ftell(pb);
  925. len = get_buffer(pb, buf, sizeof(buf));
  926. if (len != sizeof(buf))
  927. goto fail;
  928. ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
  929. if (ts->raw_packet_size <= 0)
  930. goto fail;
  931. ts->stream = s;
  932. ts->auto_guess = 0;
  933. if (!ts->mpeg2ts_raw) {
  934. /* normal demux */
  935. if (!ts->auto_guess) {
  936. ts->set_service_ret = -1;
  937. /* first do a scaning to get all the services */
  938. url_fseek(pb, pos, SEEK_SET);
  939. mpegts_scan_sdt(ts);
  940. handle_packets(ts, MAX_SCAN_PACKETS);
  941. if (ts->nb_services <= 0) {
  942. /* no SDT found, we try to look at the PAT */
  943. /* First remove the SDT filters from each PID */
  944. int i;
  945. for (i=0; i < NB_PID_MAX; i++) {
  946. if (ts->pids[i])
  947. mpegts_close_filter(ts, ts->pids[i]);
  948. }
  949. url_fseek(pb, pos, SEEK_SET);
  950. mpegts_scan_pat(ts);
  951. handle_packets(ts, MAX_SCAN_PACKETS);
  952. }
  953. if (ts->nb_services <= 0)
  954. return -1;
  955. /* tune to first service found */
  956. service = ts->services[0];
  957. sid = service->sid;
  958. #ifdef DEBUG_SI
  959. printf("tuning to '%s'\n", service->name);
  960. #endif
  961. /* now find the info for the first service if we found any,
  962. otherwise try to filter all PATs */
  963. url_fseek(pb, pos, SEEK_SET);
  964. mpegts_set_service(ts, sid, set_service_cb, ts);
  965. handle_packets(ts, MAX_SCAN_PACKETS);
  966. /* if could not find service, exit */
  967. if (ts->set_service_ret != 0)
  968. return -1;
  969. #ifdef DEBUG_SI
  970. printf("tuning done\n");
  971. #endif
  972. }
  973. s->ctx_flags |= AVFMTCTX_NOHEADER;
  974. } else {
  975. AVStream *st;
  976. int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
  977. int64_t pcrs[2], pcr_h;
  978. int packet_count[2];
  979. uint8_t packet[TS_PACKET_SIZE];
  980. /* only read packets */
  981. s->pts_num = 1;
  982. s->pts_den = 27000000;
  983. st = av_new_stream(s, 0);
  984. if (!st)
  985. goto fail;
  986. st->codec.codec_type = CODEC_TYPE_DATA;
  987. st->codec.codec_id = CODEC_ID_MPEG2TS;
  988. /* we iterate until we find two PCRs to estimate the bitrate */
  989. pcr_pid = -1;
  990. nb_pcrs = 0;
  991. nb_packets = 0;
  992. for(;;) {
  993. ret = read_packet(&s->pb, packet, ts->raw_packet_size);
  994. if (ret < 0)
  995. return -1;
  996. pid = ((packet[1] & 0x1f) << 8) | packet[2];
  997. if ((pcr_pid == -1 || pcr_pid == pid) &&
  998. parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
  999. pcr_pid = pid;
  1000. packet_count[nb_pcrs] = nb_packets;
  1001. pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
  1002. nb_pcrs++;
  1003. if (nb_pcrs >= 2)
  1004. break;
  1005. }
  1006. nb_packets++;
  1007. }
  1008. /* NOTE1: the bitrate is computed without the FEC */
  1009. /* NOTE2: it is only the bitrate of the start of the stream */
  1010. ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
  1011. ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
  1012. s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
  1013. st->codec.bit_rate = s->bit_rate;
  1014. st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
  1015. #if 0
  1016. printf("start=%0.3f pcr=%0.3f incr=%d\n",
  1017. st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
  1018. #endif
  1019. }
  1020. url_fseek(pb, pos, SEEK_SET);
  1021. return 0;
  1022. fail:
  1023. return -1;
  1024. }
  1025. #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
  1026. static int mpegts_raw_read_packet(AVFormatContext *s,
  1027. AVPacket *pkt)
  1028. {
  1029. MpegTSContext *ts = s->priv_data;
  1030. int ret, i;
  1031. int64_t pcr_h, next_pcr_h, pos;
  1032. int pcr_l, next_pcr_l;
  1033. uint8_t pcr_buf[12];
  1034. if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
  1035. return -ENOMEM;
  1036. ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
  1037. if (ret < 0) {
  1038. av_free_packet(pkt);
  1039. return ret;
  1040. }
  1041. if (ts->mpeg2ts_compute_pcr) {
  1042. /* compute exact PCR for each packet */
  1043. if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
  1044. /* we read the next PCR (XXX: optimize it by using a bigger buffer */
  1045. pos = url_ftell(&s->pb);
  1046. for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
  1047. url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
  1048. get_buffer(&s->pb, pcr_buf, 12);
  1049. if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
  1050. /* XXX: not precise enough */
  1051. ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
  1052. (i + 1);
  1053. break;
  1054. }
  1055. }
  1056. url_fseek(&s->pb, pos, SEEK_SET);
  1057. /* no next PCR found: we use previous increment */
  1058. ts->cur_pcr = pcr_h * 300 + pcr_l;
  1059. }
  1060. pkt->pts = ts->cur_pcr;
  1061. pkt->duration = ts->pcr_incr;
  1062. ts->cur_pcr += ts->pcr_incr;
  1063. }
  1064. pkt->stream_index = 0;
  1065. return 0;
  1066. }
  1067. static int mpegts_read_packet(AVFormatContext *s,
  1068. AVPacket *pkt)
  1069. {
  1070. MpegTSContext *ts = s->priv_data;
  1071. if (!ts->mpeg2ts_raw) {
  1072. ts->pkt = pkt;
  1073. return handle_packets(ts, 0);
  1074. } else {
  1075. return mpegts_raw_read_packet(s, pkt);
  1076. }
  1077. }
  1078. static int mpegts_read_close(AVFormatContext *s)
  1079. {
  1080. MpegTSContext *ts = s->priv_data;
  1081. int i;
  1082. for(i=0;i<NB_PID_MAX;i++)
  1083. av_free(ts->pids[i]);
  1084. return 0;
  1085. }
  1086. /**************************************************************/
  1087. /* parsing functions - called from other demuxers such as RTP */
  1088. MpegTSContext *mpegts_parse_open(AVFormatContext *s)
  1089. {
  1090. MpegTSContext *ts;
  1091. ts = av_mallocz(sizeof(MpegTSContext));
  1092. if (!ts)
  1093. return NULL;
  1094. /* no stream case, currently used by RTP */
  1095. ts->raw_packet_size = TS_PACKET_SIZE;
  1096. ts->stream = s;
  1097. ts->auto_guess = 1;
  1098. return ts;
  1099. }
  1100. /* return the consumed length if a packet was output, or -1 if no
  1101. packet is output */
  1102. int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
  1103. const uint8_t *buf, int len)
  1104. {
  1105. int len1;
  1106. len1 = len;
  1107. ts->pkt = pkt;
  1108. ts->stop_parse = 0;
  1109. for(;;) {
  1110. if (ts->stop_parse)
  1111. break;
  1112. if (len < TS_PACKET_SIZE)
  1113. return -1;
  1114. if (buf[0] != 0x47) {
  1115. buf--;
  1116. len--;
  1117. } else {
  1118. handle_packet(ts, buf);
  1119. buf += TS_PACKET_SIZE;
  1120. len -= TS_PACKET_SIZE;
  1121. }
  1122. }
  1123. return len1 - len;
  1124. }
  1125. void mpegts_parse_close(MpegTSContext *ts)
  1126. {
  1127. int i;
  1128. for(i=0;i<NB_PID_MAX;i++)
  1129. av_free(ts->pids[i]);
  1130. av_free(ts);
  1131. }
  1132. AVInputFormat mpegts_demux = {
  1133. "mpegts",
  1134. "MPEG2 transport stream format",
  1135. sizeof(MpegTSContext),
  1136. mpegts_probe,
  1137. mpegts_read_header,
  1138. mpegts_read_packet,
  1139. mpegts_read_close,
  1140. .flags = AVFMT_SHOW_IDS,
  1141. };
  1142. int mpegts_init(void)
  1143. {
  1144. av_register_input_format(&mpegts_demux);
  1145. #ifdef CONFIG_ENCODERS
  1146. av_register_output_format(&mpegts_mux);
  1147. #endif
  1148. return 0;
  1149. }