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.

1006 lines
32KB

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