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.

976 lines
31KB

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