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.

1039 lines
34KB

  1. /*
  2. * MPEG1/2 demuxer
  3. * Copyright (c) 2000, 2001, 2002 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 "avformat.h"
  22. #include "internal.h"
  23. #include "mpeg.h"
  24. #if CONFIG_VOBSUB_DEMUXER
  25. # include "subtitles.h"
  26. # include "libavutil/bprint.h"
  27. # include "libavutil/opt.h"
  28. #endif
  29. #include "libavutil/avassert.h"
  30. /*********************************************/
  31. /* demux code */
  32. #define MAX_SYNC_SIZE 100000
  33. static int check_pes(const uint8_t *p, const uint8_t *end)
  34. {
  35. int pes1;
  36. int pes2 = (p[3] & 0xC0) == 0x80 &&
  37. (p[4] & 0xC0) != 0x40 &&
  38. ((p[4] & 0xC0) == 0x00 ||
  39. (p[4] & 0xC0) >> 2 == (p[6] & 0xF0));
  40. for (p += 3; p < end && *p == 0xFF; p++) ;
  41. if ((*p & 0xC0) == 0x40)
  42. p += 2;
  43. if ((*p & 0xF0) == 0x20)
  44. pes1 = p[0] & p[2] & p[4] & 1;
  45. else if ((*p & 0xF0) == 0x30)
  46. pes1 = p[0] & p[2] & p[4] & p[5] & p[7] & p[9] & 1;
  47. else
  48. pes1 = *p == 0x0F;
  49. return pes1 || pes2;
  50. }
  51. static int check_pack_header(const uint8_t *buf)
  52. {
  53. return (buf[1] & 0xC0) == 0x40 || (buf[1] & 0xF0) == 0x20;
  54. }
  55. static int mpegps_probe(AVProbeData *p)
  56. {
  57. uint32_t code = -1;
  58. int i;
  59. int sys = 0, pspack = 0, priv1 = 0, vid = 0;
  60. int audio = 0, invalid = 0, score = 0;
  61. int endpes = 0;
  62. for (i = 0; i < p->buf_size; i++) {
  63. code = (code << 8) + p->buf[i];
  64. if ((code & 0xffffff00) == 0x100) {
  65. int len = p->buf[i + 1] << 8 | p->buf[i + 2];
  66. int pes = endpes <= i && check_pes(p->buf + i, p->buf + p->buf_size);
  67. int pack = check_pack_header(p->buf + i);
  68. if (code == SYSTEM_HEADER_START_CODE)
  69. sys++;
  70. else if (code == PACK_START_CODE && pack)
  71. pspack++;
  72. else if ((code & 0xf0) == VIDEO_ID && pes) {
  73. endpes = i + len;
  74. vid++;
  75. }
  76. // skip pes payload to avoid start code emulation for private
  77. // and audio streams
  78. else if ((code & 0xe0) == AUDIO_ID && pes) {audio++; i+=len;}
  79. else if (code == PRIVATE_STREAM_1 && pes) {priv1++; i+=len;}
  80. else if (code == 0x1fd && pes) vid++; //VC1
  81. else if ((code & 0xf0) == VIDEO_ID && !pes) invalid++;
  82. else if ((code & 0xe0) == AUDIO_ID && !pes) invalid++;
  83. else if (code == PRIVATE_STREAM_1 && !pes) invalid++;
  84. }
  85. }
  86. if (vid + audio > invalid + 1) /* invalid VDR files nd short PES streams */
  87. score = AVPROBE_SCORE_EXTENSION / 2;
  88. // av_log(NULL, AV_LOG_ERROR, "vid:%d aud:%d sys:%d pspack:%d invalid:%d size:%d \n",
  89. // vid, audio, sys, pspack, invalid, p->buf_size);
  90. if (sys > invalid && sys * 9 <= pspack * 10)
  91. return (audio > 12 || vid > 3 || pspack > 2) ? AVPROBE_SCORE_EXTENSION + 2
  92. : AVPROBE_SCORE_EXTENSION / 2 + 1; // 1 more than mp3
  93. if (pspack > invalid && (priv1 + vid + audio) * 10 >= pspack * 9)
  94. return pspack > 2 ? AVPROBE_SCORE_EXTENSION + 2
  95. : AVPROBE_SCORE_EXTENSION / 2; // 1 more than .mpg
  96. if ((!!vid ^ !!audio) && (audio > 4 || vid > 1) && !sys &&
  97. !pspack && p->buf_size > 2048 && vid + audio > invalid) /* PES stream */
  98. return (audio > 12 || vid > 3 + 2 * invalid) ? AVPROBE_SCORE_EXTENSION + 2
  99. : AVPROBE_SCORE_EXTENSION / 2;
  100. // 02-Penguin.flac has sys:0 priv1:0 pspack:0 vid:0 audio:1
  101. // mp3_misidentified_2.mp3 has sys:0 priv1:0 pspack:0 vid:0 audio:6
  102. // Have\ Yourself\ a\ Merry\ Little\ Christmas.mp3 0 0 0 5 0 1 len:21618
  103. return score;
  104. }
  105. typedef struct MpegDemuxContext {
  106. AVClass *class;
  107. int32_t header_state;
  108. unsigned char psm_es_type[256];
  109. int sofdec;
  110. int dvd;
  111. int imkh_cctv;
  112. #if CONFIG_VOBSUB_DEMUXER
  113. AVFormatContext *sub_ctx;
  114. FFDemuxSubtitlesQueue q[32];
  115. char *sub_name;
  116. #endif
  117. } MpegDemuxContext;
  118. static int mpegps_read_header(AVFormatContext *s)
  119. {
  120. MpegDemuxContext *m = s->priv_data;
  121. char buffer[7];
  122. int64_t last_pos = avio_tell(s->pb);
  123. m->header_state = 0xff;
  124. s->ctx_flags |= AVFMTCTX_NOHEADER;
  125. avio_get_str(s->pb, 6, buffer, sizeof(buffer));
  126. if (!memcmp("IMKH", buffer, 4)) {
  127. m->imkh_cctv = 1;
  128. } else if (!memcmp("Sofdec", buffer, 6)) {
  129. m->sofdec = 1;
  130. } else
  131. avio_seek(s->pb, last_pos, SEEK_SET);
  132. /* no need to do more */
  133. return 0;
  134. }
  135. static int64_t get_pts(AVIOContext *pb, int c)
  136. {
  137. uint8_t buf[5];
  138. buf[0] = c < 0 ? avio_r8(pb) : c;
  139. avio_read(pb, buf + 1, 4);
  140. return ff_parse_pes_pts(buf);
  141. }
  142. static int find_next_start_code(AVIOContext *pb, int *size_ptr,
  143. int32_t *header_state)
  144. {
  145. unsigned int state, v;
  146. int val, n;
  147. state = *header_state;
  148. n = *size_ptr;
  149. while (n > 0) {
  150. if (avio_feof(pb))
  151. break;
  152. v = avio_r8(pb);
  153. n--;
  154. if (state == 0x000001) {
  155. state = ((state << 8) | v) & 0xffffff;
  156. val = state;
  157. goto found;
  158. }
  159. state = ((state << 8) | v) & 0xffffff;
  160. }
  161. val = -1;
  162. found:
  163. *header_state = state;
  164. *size_ptr = n;
  165. return val;
  166. }
  167. /**
  168. * Extract stream types from a program stream map
  169. * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
  170. *
  171. * @return number of bytes occupied by PSM in the bitstream
  172. */
  173. static long mpegps_psm_parse(MpegDemuxContext *m, AVIOContext *pb)
  174. {
  175. int psm_length, ps_info_length, es_map_length;
  176. psm_length = avio_rb16(pb);
  177. avio_r8(pb);
  178. avio_r8(pb);
  179. ps_info_length = avio_rb16(pb);
  180. /* skip program_stream_info */
  181. avio_skip(pb, ps_info_length);
  182. /*es_map_length = */avio_rb16(pb);
  183. /* Ignore es_map_length, trust psm_length */
  184. es_map_length = psm_length - ps_info_length - 10;
  185. /* at least one es available? */
  186. while (es_map_length >= 4) {
  187. unsigned char type = avio_r8(pb);
  188. unsigned char es_id = avio_r8(pb);
  189. uint16_t es_info_length = avio_rb16(pb);
  190. /* remember mapping from stream id to stream type */
  191. m->psm_es_type[es_id] = type;
  192. /* skip program_stream_info */
  193. avio_skip(pb, es_info_length);
  194. es_map_length -= 4 + es_info_length;
  195. }
  196. avio_rb32(pb); /* crc32 */
  197. return 2 + psm_length;
  198. }
  199. /* read the next PES header. Return its position in ppos
  200. * (if not NULL), and its start code, pts and dts.
  201. */
  202. static int mpegps_read_pes_header(AVFormatContext *s,
  203. int64_t *ppos, int *pstart_code,
  204. int64_t *ppts, int64_t *pdts)
  205. {
  206. MpegDemuxContext *m = s->priv_data;
  207. int len, size, startcode, c, flags, header_len;
  208. int pes_ext, ext2_len, id_ext, skip;
  209. int64_t pts, dts;
  210. int64_t last_sync = avio_tell(s->pb);
  211. error_redo:
  212. avio_seek(s->pb, last_sync, SEEK_SET);
  213. redo:
  214. /* next start code (should be immediately after) */
  215. m->header_state = 0xff;
  216. size = MAX_SYNC_SIZE;
  217. startcode = find_next_start_code(s->pb, &size, &m->header_state);
  218. last_sync = avio_tell(s->pb);
  219. if (startcode < 0) {
  220. if (avio_feof(s->pb))
  221. return AVERROR_EOF;
  222. // FIXME we should remember header_state
  223. return AVERROR(EAGAIN);
  224. }
  225. if (startcode == PACK_START_CODE)
  226. goto redo;
  227. if (startcode == SYSTEM_HEADER_START_CODE)
  228. goto redo;
  229. if (startcode == PADDING_STREAM) {
  230. avio_skip(s->pb, avio_rb16(s->pb));
  231. goto redo;
  232. }
  233. if (startcode == PRIVATE_STREAM_2) {
  234. if (!m->sofdec) {
  235. /* Need to detect whether this from a DVD or a 'Sofdec' stream */
  236. int len = avio_rb16(s->pb);
  237. int bytesread = 0;
  238. uint8_t *ps2buf = av_malloc(len);
  239. if (ps2buf) {
  240. bytesread = avio_read(s->pb, ps2buf, len);
  241. if (bytesread != len) {
  242. avio_skip(s->pb, len - bytesread);
  243. } else {
  244. uint8_t *p = 0;
  245. if (len >= 6)
  246. p = memchr(ps2buf, 'S', len - 5);
  247. if (p)
  248. m->sofdec = !memcmp(p+1, "ofdec", 5);
  249. m->sofdec -= !m->sofdec;
  250. if (m->sofdec < 0) {
  251. if (len == 980 && ps2buf[0] == 0) {
  252. /* PCI structure? */
  253. uint32_t startpts = AV_RB32(ps2buf + 0x0d);
  254. uint32_t endpts = AV_RB32(ps2buf + 0x11);
  255. uint8_t hours = ((ps2buf[0x19] >> 4) * 10) + (ps2buf[0x19] & 0x0f);
  256. uint8_t mins = ((ps2buf[0x1a] >> 4) * 10) + (ps2buf[0x1a] & 0x0f);
  257. uint8_t secs = ((ps2buf[0x1b] >> 4) * 10) + (ps2buf[0x1b] & 0x0f);
  258. m->dvd = (hours <= 23 &&
  259. mins <= 59 &&
  260. secs <= 59 &&
  261. (ps2buf[0x19] & 0x0f) < 10 &&
  262. (ps2buf[0x1a] & 0x0f) < 10 &&
  263. (ps2buf[0x1b] & 0x0f) < 10 &&
  264. endpts >= startpts);
  265. } else if (len == 1018 && ps2buf[0] == 1) {
  266. /* DSI structure? */
  267. uint8_t hours = ((ps2buf[0x1d] >> 4) * 10) + (ps2buf[0x1d] & 0x0f);
  268. uint8_t mins = ((ps2buf[0x1e] >> 4) * 10) + (ps2buf[0x1e] & 0x0f);
  269. uint8_t secs = ((ps2buf[0x1f] >> 4) * 10) + (ps2buf[0x1f] & 0x0f);
  270. m->dvd = (hours <= 23 &&
  271. mins <= 59 &&
  272. secs <= 59 &&
  273. (ps2buf[0x1d] & 0x0f) < 10 &&
  274. (ps2buf[0x1e] & 0x0f) < 10 &&
  275. (ps2buf[0x1f] & 0x0f) < 10);
  276. }
  277. }
  278. }
  279. av_free(ps2buf);
  280. /* If this isn't a DVD packet or no memory
  281. * could be allocated, just ignore it.
  282. * If we did, move back to the start of the
  283. * packet (plus 'length' field) */
  284. if (!m->dvd || avio_skip(s->pb, -(len + 2)) < 0) {
  285. /* Skip back failed.
  286. * This packet will be lost but that can't be helped
  287. * if we can't skip back
  288. */
  289. goto redo;
  290. }
  291. } else {
  292. /* No memory */
  293. avio_skip(s->pb, len);
  294. goto redo;
  295. }
  296. } else if (!m->dvd) {
  297. int len = avio_rb16(s->pb);
  298. avio_skip(s->pb, len);
  299. goto redo;
  300. }
  301. }
  302. if (startcode == PROGRAM_STREAM_MAP) {
  303. mpegps_psm_parse(m, s->pb);
  304. goto redo;
  305. }
  306. /* find matching stream */
  307. if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
  308. (startcode >= 0x1e0 && startcode <= 0x1ef) ||
  309. (startcode == 0x1bd) ||
  310. (startcode == PRIVATE_STREAM_2) ||
  311. (startcode == 0x1fd)))
  312. goto redo;
  313. if (ppos) {
  314. *ppos = avio_tell(s->pb) - 4;
  315. }
  316. len = avio_rb16(s->pb);
  317. pts =
  318. dts = AV_NOPTS_VALUE;
  319. if (startcode != PRIVATE_STREAM_2)
  320. {
  321. /* stuffing */
  322. for (;;) {
  323. if (len < 1)
  324. goto error_redo;
  325. c = avio_r8(s->pb);
  326. len--;
  327. /* XXX: for mpeg1, should test only bit 7 */
  328. if (c != 0xff)
  329. break;
  330. }
  331. if ((c & 0xc0) == 0x40) {
  332. /* buffer scale & size */
  333. avio_r8(s->pb);
  334. c = avio_r8(s->pb);
  335. len -= 2;
  336. }
  337. if ((c & 0xe0) == 0x20) {
  338. dts =
  339. pts = get_pts(s->pb, c);
  340. len -= 4;
  341. if (c & 0x10) {
  342. dts = get_pts(s->pb, -1);
  343. len -= 5;
  344. }
  345. } else if ((c & 0xc0) == 0x80) {
  346. /* mpeg 2 PES */
  347. flags = avio_r8(s->pb);
  348. header_len = avio_r8(s->pb);
  349. len -= 2;
  350. if (header_len > len)
  351. goto error_redo;
  352. len -= header_len;
  353. if (flags & 0x80) {
  354. dts = pts = get_pts(s->pb, -1);
  355. header_len -= 5;
  356. if (flags & 0x40) {
  357. dts = get_pts(s->pb, -1);
  358. header_len -= 5;
  359. }
  360. }
  361. if (flags & 0x3f && header_len == 0) {
  362. flags &= 0xC0;
  363. av_log(s, AV_LOG_WARNING, "Further flags set but no bytes left\n");
  364. }
  365. if (flags & 0x01) { /* PES extension */
  366. pes_ext = avio_r8(s->pb);
  367. header_len--;
  368. /* Skip PES private data, program packet sequence counter
  369. * and P-STD buffer */
  370. skip = (pes_ext >> 4) & 0xb;
  371. skip += skip & 0x9;
  372. if (pes_ext & 0x40 || skip > header_len) {
  373. av_log(s, AV_LOG_WARNING, "pes_ext %X is invalid\n", pes_ext);
  374. pes_ext = skip = 0;
  375. }
  376. avio_skip(s->pb, skip);
  377. header_len -= skip;
  378. if (pes_ext & 0x01) { /* PES extension 2 */
  379. ext2_len = avio_r8(s->pb);
  380. header_len--;
  381. if ((ext2_len & 0x7f) > 0) {
  382. id_ext = avio_r8(s->pb);
  383. if ((id_ext & 0x80) == 0)
  384. startcode = ((startcode & 0xff) << 8) | id_ext;
  385. header_len--;
  386. }
  387. }
  388. }
  389. if (header_len < 0)
  390. goto error_redo;
  391. avio_skip(s->pb, header_len);
  392. } else if (c != 0xf)
  393. goto redo;
  394. }
  395. if (startcode == PRIVATE_STREAM_1) {
  396. startcode = avio_r8(s->pb);
  397. len--;
  398. }
  399. if (len < 0)
  400. goto error_redo;
  401. if (dts != AV_NOPTS_VALUE && ppos) {
  402. int i;
  403. for (i = 0; i < s->nb_streams; i++) {
  404. if (startcode == s->streams[i]->id &&
  405. s->pb->seekable /* index useless on streams anyway */) {
  406. ff_reduce_index(s, i);
  407. av_add_index_entry(s->streams[i], *ppos, dts, 0, 0,
  408. AVINDEX_KEYFRAME /* FIXME keyframe? */);
  409. }
  410. }
  411. }
  412. *pstart_code = startcode;
  413. *ppts = pts;
  414. *pdts = dts;
  415. return len;
  416. }
  417. static int mpegps_read_packet(AVFormatContext *s,
  418. AVPacket *pkt)
  419. {
  420. MpegDemuxContext *m = s->priv_data;
  421. AVStream *st;
  422. int len, startcode, i, es_type, ret;
  423. int lpcm_header_len = -1; //Init to suppress warning
  424. int request_probe= 0;
  425. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  426. enum AVMediaType type;
  427. int64_t pts, dts, dummy_pos; // dummy_pos is needed for the index building to work
  428. redo:
  429. len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
  430. if (len < 0)
  431. return len;
  432. if (startcode >= 0x80 && startcode <= 0xcf) {
  433. if (len < 4)
  434. goto skip;
  435. /* audio: skip header */
  436. avio_r8(s->pb);
  437. lpcm_header_len = avio_rb16(s->pb);
  438. len -= 3;
  439. if (startcode >= 0xb0 && startcode <= 0xbf) {
  440. /* MLP/TrueHD audio has a 4-byte header */
  441. avio_r8(s->pb);
  442. len--;
  443. }
  444. }
  445. /* now find stream */
  446. for (i = 0; i < s->nb_streams; i++) {
  447. st = s->streams[i];
  448. if (st->id == startcode)
  449. goto found;
  450. }
  451. es_type = m->psm_es_type[startcode & 0xff];
  452. if (es_type == STREAM_TYPE_VIDEO_MPEG1) {
  453. codec_id = AV_CODEC_ID_MPEG2VIDEO;
  454. type = AVMEDIA_TYPE_VIDEO;
  455. } else if (es_type == STREAM_TYPE_VIDEO_MPEG2) {
  456. codec_id = AV_CODEC_ID_MPEG2VIDEO;
  457. type = AVMEDIA_TYPE_VIDEO;
  458. } else if (es_type == STREAM_TYPE_AUDIO_MPEG1 ||
  459. es_type == STREAM_TYPE_AUDIO_MPEG2) {
  460. codec_id = AV_CODEC_ID_MP3;
  461. type = AVMEDIA_TYPE_AUDIO;
  462. } else if (es_type == STREAM_TYPE_AUDIO_AAC) {
  463. codec_id = AV_CODEC_ID_AAC;
  464. type = AVMEDIA_TYPE_AUDIO;
  465. } else if (es_type == STREAM_TYPE_VIDEO_MPEG4) {
  466. codec_id = AV_CODEC_ID_MPEG4;
  467. type = AVMEDIA_TYPE_VIDEO;
  468. } else if (es_type == STREAM_TYPE_VIDEO_H264) {
  469. codec_id = AV_CODEC_ID_H264;
  470. type = AVMEDIA_TYPE_VIDEO;
  471. } else if (es_type == STREAM_TYPE_AUDIO_AC3) {
  472. codec_id = AV_CODEC_ID_AC3;
  473. type = AVMEDIA_TYPE_AUDIO;
  474. } else if (m->imkh_cctv && es_type == 0x91) {
  475. codec_id = AV_CODEC_ID_PCM_MULAW;
  476. type = AVMEDIA_TYPE_AUDIO;
  477. } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
  478. static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
  479. unsigned char buf[8];
  480. avio_read(s->pb, buf, 8);
  481. avio_seek(s->pb, -8, SEEK_CUR);
  482. if (!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1))
  483. codec_id = AV_CODEC_ID_CAVS;
  484. else
  485. request_probe= 1;
  486. type = AVMEDIA_TYPE_VIDEO;
  487. } else if (startcode == PRIVATE_STREAM_2) {
  488. type = AVMEDIA_TYPE_DATA;
  489. codec_id = AV_CODEC_ID_DVD_NAV;
  490. } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
  491. type = AVMEDIA_TYPE_AUDIO;
  492. if (m->sofdec > 0) {
  493. codec_id = AV_CODEC_ID_ADPCM_ADX;
  494. // Auto-detect AC-3
  495. request_probe = 50;
  496. } else if (m->imkh_cctv && startcode == 0x1c0 && len > 80) {
  497. codec_id = AV_CODEC_ID_PCM_ALAW;
  498. request_probe = 50;
  499. } else {
  500. codec_id = AV_CODEC_ID_MP2;
  501. if (m->imkh_cctv)
  502. request_probe = 25;
  503. }
  504. } else if (startcode >= 0x80 && startcode <= 0x87) {
  505. type = AVMEDIA_TYPE_AUDIO;
  506. codec_id = AV_CODEC_ID_AC3;
  507. } else if ((startcode >= 0x88 && startcode <= 0x8f) ||
  508. (startcode >= 0x98 && startcode <= 0x9f)) {
  509. /* 0x90 - 0x97 is reserved for SDDS in DVD specs */
  510. type = AVMEDIA_TYPE_AUDIO;
  511. codec_id = AV_CODEC_ID_DTS;
  512. } else if (startcode >= 0xa0 && startcode <= 0xaf) {
  513. type = AVMEDIA_TYPE_AUDIO;
  514. if (lpcm_header_len == 6) {
  515. codec_id = AV_CODEC_ID_MLP;
  516. } else {
  517. codec_id = AV_CODEC_ID_PCM_DVD;
  518. }
  519. } else if (startcode >= 0xb0 && startcode <= 0xbf) {
  520. type = AVMEDIA_TYPE_AUDIO;
  521. codec_id = AV_CODEC_ID_TRUEHD;
  522. } else if (startcode >= 0xc0 && startcode <= 0xcf) {
  523. /* Used for both AC-3 and E-AC-3 in EVOB files */
  524. type = AVMEDIA_TYPE_AUDIO;
  525. codec_id = AV_CODEC_ID_AC3;
  526. } else if (startcode >= 0x20 && startcode <= 0x3f) {
  527. type = AVMEDIA_TYPE_SUBTITLE;
  528. codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  529. } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) {
  530. type = AVMEDIA_TYPE_VIDEO;
  531. codec_id = AV_CODEC_ID_VC1;
  532. } else {
  533. skip:
  534. /* skip packet */
  535. avio_skip(s->pb, len);
  536. goto redo;
  537. }
  538. /* no stream found: add a new stream */
  539. st = avformat_new_stream(s, NULL);
  540. if (!st)
  541. goto skip;
  542. st->id = startcode;
  543. st->codec->codec_type = type;
  544. st->codec->codec_id = codec_id;
  545. if ( st->codec->codec_id == AV_CODEC_ID_PCM_MULAW
  546. || st->codec->codec_id == AV_CODEC_ID_PCM_ALAW) {
  547. st->codec->channels = 1;
  548. st->codec->channel_layout = AV_CH_LAYOUT_MONO;
  549. st->codec->sample_rate = 8000;
  550. }
  551. st->request_probe = request_probe;
  552. st->need_parsing = AVSTREAM_PARSE_FULL;
  553. found:
  554. if (st->discard >= AVDISCARD_ALL)
  555. goto skip;
  556. if (startcode >= 0xa0 && startcode <= 0xaf) {
  557. if (st->codec->codec_id == AV_CODEC_ID_MLP) {
  558. if (len < 6)
  559. goto skip;
  560. avio_skip(s->pb, 6);
  561. len -=6;
  562. }
  563. }
  564. ret = av_get_packet(s->pb, pkt, len);
  565. pkt->pts = pts;
  566. pkt->dts = dts;
  567. pkt->pos = dummy_pos;
  568. pkt->stream_index = st->index;
  569. if (s->debug & FF_FDEBUG_TS)
  570. av_log(s, AV_LOG_TRACE, "%d: pts=%0.3f dts=%0.3f size=%d\n",
  571. pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0,
  572. pkt->size);
  573. return (ret < 0) ? ret : 0;
  574. }
  575. static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
  576. int64_t *ppos, int64_t pos_limit)
  577. {
  578. int len, startcode;
  579. int64_t pos, pts, dts;
  580. pos = *ppos;
  581. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  582. return AV_NOPTS_VALUE;
  583. for (;;) {
  584. len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
  585. if (len < 0) {
  586. if (s->debug & FF_FDEBUG_TS)
  587. av_log(s, AV_LOG_TRACE, "none (ret=%d)\n", len);
  588. return AV_NOPTS_VALUE;
  589. }
  590. if (startcode == s->streams[stream_index]->id &&
  591. dts != AV_NOPTS_VALUE) {
  592. break;
  593. }
  594. avio_skip(s->pb, len);
  595. }
  596. if (s->debug & FF_FDEBUG_TS)
  597. av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n",
  598. pos, dts, dts / 90000.0);
  599. *ppos = pos;
  600. return dts;
  601. }
  602. AVInputFormat ff_mpegps_demuxer = {
  603. .name = "mpeg",
  604. .long_name = NULL_IF_CONFIG_SMALL("MPEG-PS (MPEG-2 Program Stream)"),
  605. .priv_data_size = sizeof(MpegDemuxContext),
  606. .read_probe = mpegps_probe,
  607. .read_header = mpegps_read_header,
  608. .read_packet = mpegps_read_packet,
  609. .read_timestamp = mpegps_read_dts,
  610. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  611. };
  612. #if CONFIG_VOBSUB_DEMUXER
  613. #define REF_STRING "# VobSub index file,"
  614. #define MAX_LINE_SIZE 2048
  615. static int vobsub_probe(AVProbeData *p)
  616. {
  617. if (!strncmp(p->buf, REF_STRING, sizeof(REF_STRING) - 1))
  618. return AVPROBE_SCORE_MAX;
  619. return 0;
  620. }
  621. static int vobsub_read_header(AVFormatContext *s)
  622. {
  623. int i, ret = 0, header_parsed = 0, langidx = 0;
  624. MpegDemuxContext *vobsub = s->priv_data;
  625. size_t fname_len;
  626. char *header_str;
  627. AVBPrint header;
  628. int64_t delay = 0;
  629. AVStream *st = NULL;
  630. int stream_id = -1;
  631. char id[64] = {0};
  632. char alt[MAX_LINE_SIZE] = {0};
  633. AVInputFormat *iformat;
  634. if (!vobsub->sub_name) {
  635. char *ext;
  636. vobsub->sub_name = av_strdup(s->filename);
  637. if (!vobsub->sub_name) {
  638. ret = AVERROR(ENOMEM);
  639. goto end;
  640. }
  641. fname_len = strlen(vobsub->sub_name);
  642. ext = vobsub->sub_name - 3 + fname_len;
  643. if (fname_len < 4 || *(ext - 1) != '.') {
  644. av_log(s, AV_LOG_ERROR, "The input index filename is too short "
  645. "to guess the associated .SUB file\n");
  646. ret = AVERROR_INVALIDDATA;
  647. goto end;
  648. }
  649. memcpy(ext, !strncmp(ext, "IDX", 3) ? "SUB" : "sub", 3);
  650. av_log(s, AV_LOG_VERBOSE, "IDX/SUB: %s -> %s\n", s->filename, vobsub->sub_name);
  651. }
  652. if (!(iformat = av_find_input_format("mpeg"))) {
  653. ret = AVERROR_DEMUXER_NOT_FOUND;
  654. goto end;
  655. }
  656. vobsub->sub_ctx = avformat_alloc_context();
  657. if (!vobsub->sub_ctx) {
  658. ret = AVERROR(ENOMEM);
  659. goto end;
  660. }
  661. if ((ret = ff_copy_whitelists(vobsub->sub_ctx, s)) < 0)
  662. goto end;
  663. ret = avformat_open_input(&vobsub->sub_ctx, vobsub->sub_name, iformat, NULL);
  664. if (ret < 0) {
  665. av_log(s, AV_LOG_ERROR, "Unable to open %s as MPEG subtitles\n", vobsub->sub_name);
  666. goto end;
  667. }
  668. av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED);
  669. while (!avio_feof(s->pb)) {
  670. char line[MAX_LINE_SIZE];
  671. int len = ff_get_line(s->pb, line, sizeof(line));
  672. if (!len)
  673. break;
  674. line[strcspn(line, "\r\n")] = 0;
  675. if (!strncmp(line, "id:", 3)) {
  676. if (sscanf(line, "id: %63[^,], index: %u", id, &stream_id) != 2) {
  677. av_log(s, AV_LOG_WARNING, "Unable to parse index line '%s', "
  678. "assuming 'id: und, index: 0'\n", line);
  679. strcpy(id, "und");
  680. stream_id = 0;
  681. }
  682. if (stream_id >= FF_ARRAY_ELEMS(vobsub->q)) {
  683. av_log(s, AV_LOG_ERROR, "Maximum number of subtitles streams reached\n");
  684. ret = AVERROR(EINVAL);
  685. goto end;
  686. }
  687. header_parsed = 1;
  688. alt[0] = '\0';
  689. /* We do not create the stream immediately to avoid adding empty
  690. * streams. See the following timestamp entry. */
  691. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] id=%s\n", stream_id, id);
  692. } else if (!strncmp(line, "timestamp:", 10)) {
  693. AVPacket *sub;
  694. int hh, mm, ss, ms;
  695. int64_t pos, timestamp;
  696. const char *p = line + 10;
  697. if (stream_id == -1) {
  698. av_log(s, AV_LOG_ERROR, "Timestamp declared before any stream\n");
  699. ret = AVERROR_INVALIDDATA;
  700. goto end;
  701. }
  702. if (!st || st->id != stream_id) {
  703. st = avformat_new_stream(s, NULL);
  704. if (!st) {
  705. ret = AVERROR(ENOMEM);
  706. goto end;
  707. }
  708. st->id = stream_id;
  709. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  710. st->codec->codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  711. avpriv_set_pts_info(st, 64, 1, 1000);
  712. av_dict_set(&st->metadata, "language", id, 0);
  713. if (alt[0])
  714. av_dict_set(&st->metadata, "title", alt, 0);
  715. }
  716. if (sscanf(p, "%02d:%02d:%02d:%03d, filepos: %"SCNx64,
  717. &hh, &mm, &ss, &ms, &pos) != 5) {
  718. av_log(s, AV_LOG_ERROR, "Unable to parse timestamp line '%s', "
  719. "abort parsing\n", line);
  720. ret = AVERROR_INVALIDDATA;
  721. goto end;
  722. }
  723. timestamp = (hh*3600LL + mm*60LL + ss) * 1000LL + ms + delay;
  724. timestamp = av_rescale_q(timestamp, av_make_q(1, 1000), st->time_base);
  725. sub = ff_subtitles_queue_insert(&vobsub->q[s->nb_streams - 1], "", 0, 0);
  726. if (!sub) {
  727. ret = AVERROR(ENOMEM);
  728. goto end;
  729. }
  730. sub->pos = pos;
  731. sub->pts = timestamp;
  732. sub->stream_index = s->nb_streams - 1;
  733. } else if (!strncmp(line, "alt:", 4)) {
  734. const char *p = line + 4;
  735. while (*p == ' ')
  736. p++;
  737. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] name=%s\n", stream_id, p);
  738. av_strlcpy(alt, p, sizeof(alt));
  739. header_parsed = 1;
  740. } else if (!strncmp(line, "delay:", 6)) {
  741. int sign = 1, hh = 0, mm = 0, ss = 0, ms = 0;
  742. const char *p = line + 6;
  743. while (*p == ' ')
  744. p++;
  745. if (*p == '-' || *p == '+') {
  746. sign = *p == '-' ? -1 : 1;
  747. p++;
  748. }
  749. sscanf(p, "%d:%d:%d:%d", &hh, &mm, &ss, &ms);
  750. delay = ((hh*3600LL + mm*60LL + ss) * 1000LL + ms) * sign;
  751. } else if (!strncmp(line, "langidx:", 8)) {
  752. const char *p = line + 8;
  753. if (sscanf(p, "%d", &langidx) != 1)
  754. av_log(s, AV_LOG_ERROR, "Invalid langidx specified\n");
  755. } else if (!header_parsed) {
  756. if (line[0] && line[0] != '#')
  757. av_bprintf(&header, "%s\n", line);
  758. }
  759. }
  760. if (langidx < s->nb_streams)
  761. s->streams[langidx]->disposition |= AV_DISPOSITION_DEFAULT;
  762. for (i = 0; i < s->nb_streams; i++) {
  763. vobsub->q[i].sort = SUB_SORT_POS_TS;
  764. vobsub->q[i].keep_duplicates = 1;
  765. ff_subtitles_queue_finalize(s, &vobsub->q[i]);
  766. }
  767. if (!av_bprint_is_complete(&header)) {
  768. av_bprint_finalize(&header, NULL);
  769. ret = AVERROR(ENOMEM);
  770. goto end;
  771. }
  772. av_bprint_finalize(&header, &header_str);
  773. for (i = 0; i < s->nb_streams; i++) {
  774. AVStream *sub_st = s->streams[i];
  775. sub_st->codec->extradata = av_strdup(header_str);
  776. sub_st->codec->extradata_size = header.len;
  777. }
  778. av_free(header_str);
  779. end:
  780. return ret;
  781. }
  782. static int vobsub_read_packet(AVFormatContext *s, AVPacket *pkt)
  783. {
  784. MpegDemuxContext *vobsub = s->priv_data;
  785. FFDemuxSubtitlesQueue *q;
  786. AVIOContext *pb = vobsub->sub_ctx->pb;
  787. int ret, psize, total_read = 0, i;
  788. AVPacket idx_pkt;
  789. int64_t min_ts = INT64_MAX;
  790. int sid = 0;
  791. for (i = 0; i < s->nb_streams; i++) {
  792. FFDemuxSubtitlesQueue *tmpq = &vobsub->q[i];
  793. int64_t ts;
  794. av_assert0(tmpq->nb_subs);
  795. ts = tmpq->subs[tmpq->current_sub_idx].pts;
  796. if (ts < min_ts) {
  797. min_ts = ts;
  798. sid = i;
  799. }
  800. }
  801. q = &vobsub->q[sid];
  802. ret = ff_subtitles_queue_read_packet(q, &idx_pkt);
  803. if (ret < 0)
  804. return ret;
  805. /* compute maximum packet size using the next packet position. This is
  806. * useful when the len in the header is non-sense */
  807. if (q->current_sub_idx < q->nb_subs) {
  808. psize = q->subs[q->current_sub_idx].pos - idx_pkt.pos;
  809. } else {
  810. int64_t fsize = avio_size(pb);
  811. psize = fsize < 0 ? 0xffff : fsize - idx_pkt.pos;
  812. }
  813. avio_seek(pb, idx_pkt.pos, SEEK_SET);
  814. av_init_packet(pkt);
  815. pkt->size = 0;
  816. pkt->data = NULL;
  817. do {
  818. int n, to_read, startcode;
  819. int64_t pts, dts;
  820. int64_t old_pos = avio_tell(pb), new_pos;
  821. int pkt_size;
  822. ret = mpegps_read_pes_header(vobsub->sub_ctx, NULL, &startcode, &pts, &dts);
  823. if (ret < 0) {
  824. if (pkt->size) // raise packet even if incomplete
  825. break;
  826. goto fail;
  827. }
  828. to_read = ret & 0xffff;
  829. new_pos = avio_tell(pb);
  830. pkt_size = ret + (new_pos - old_pos);
  831. /* this prevents reads above the current packet */
  832. if (total_read + pkt_size > psize)
  833. break;
  834. total_read += pkt_size;
  835. /* the current chunk doesn't match the stream index (unlikely) */
  836. if ((startcode & 0x1f) != s->streams[idx_pkt.stream_index]->id)
  837. break;
  838. ret = av_grow_packet(pkt, to_read);
  839. if (ret < 0)
  840. goto fail;
  841. n = avio_read(pb, pkt->data + (pkt->size - to_read), to_read);
  842. if (n < to_read)
  843. pkt->size -= to_read - n;
  844. } while (total_read < psize);
  845. pkt->pts = pkt->dts = idx_pkt.pts;
  846. pkt->pos = idx_pkt.pos;
  847. pkt->stream_index = idx_pkt.stream_index;
  848. av_packet_unref(&idx_pkt);
  849. return 0;
  850. fail:
  851. av_packet_unref(pkt);
  852. av_packet_unref(&idx_pkt);
  853. return ret;
  854. }
  855. static int vobsub_read_seek(AVFormatContext *s, int stream_index,
  856. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  857. {
  858. MpegDemuxContext *vobsub = s->priv_data;
  859. /* Rescale requested timestamps based on the first stream (timebase is the
  860. * same for all subtitles stream within a .idx/.sub). Rescaling is done just
  861. * like in avformat_seek_file(). */
  862. if (stream_index == -1 && s->nb_streams != 1) {
  863. int i, ret = 0;
  864. AVRational time_base = s->streams[0]->time_base;
  865. ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
  866. min_ts = av_rescale_rnd(min_ts, time_base.den,
  867. time_base.num * (int64_t)AV_TIME_BASE,
  868. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  869. max_ts = av_rescale_rnd(max_ts, time_base.den,
  870. time_base.num * (int64_t)AV_TIME_BASE,
  871. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  872. for (i = 0; i < s->nb_streams; i++) {
  873. int r = ff_subtitles_queue_seek(&vobsub->q[i], s, stream_index,
  874. min_ts, ts, max_ts, flags);
  875. if (r < 0)
  876. ret = r;
  877. }
  878. return ret;
  879. }
  880. if (stream_index == -1) // only 1 stream
  881. stream_index = 0;
  882. return ff_subtitles_queue_seek(&vobsub->q[stream_index], s, stream_index,
  883. min_ts, ts, max_ts, flags);
  884. }
  885. static int vobsub_read_close(AVFormatContext *s)
  886. {
  887. int i;
  888. MpegDemuxContext *vobsub = s->priv_data;
  889. for (i = 0; i < s->nb_streams; i++)
  890. ff_subtitles_queue_clean(&vobsub->q[i]);
  891. if (vobsub->sub_ctx)
  892. avformat_close_input(&vobsub->sub_ctx);
  893. return 0;
  894. }
  895. static const AVOption options[] = {
  896. { "sub_name", "URI for .sub file", offsetof(MpegDemuxContext, sub_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
  897. { NULL }
  898. };
  899. static const AVClass vobsub_demuxer_class = {
  900. .class_name = "vobsub",
  901. .item_name = av_default_item_name,
  902. .option = options,
  903. .version = LIBAVUTIL_VERSION_INT,
  904. };
  905. AVInputFormat ff_vobsub_demuxer = {
  906. .name = "vobsub",
  907. .long_name = NULL_IF_CONFIG_SMALL("VobSub subtitle format"),
  908. .priv_data_size = sizeof(MpegDemuxContext),
  909. .read_probe = vobsub_probe,
  910. .read_header = vobsub_read_header,
  911. .read_packet = vobsub_read_packet,
  912. .read_seek2 = vobsub_read_seek,
  913. .read_close = vobsub_read_close,
  914. .flags = AVFMT_SHOW_IDS,
  915. .extensions = "idx",
  916. .priv_class = &vobsub_demuxer_class,
  917. };
  918. #endif