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.

986 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. #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 suppress 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. #define MAX_LINE_SIZE 2048
  600. static int vobsub_probe(AVProbeData *p)
  601. {
  602. if (!strncmp(p->buf, REF_STRING, sizeof(REF_STRING) - 1))
  603. return AVPROBE_SCORE_MAX;
  604. return 0;
  605. }
  606. static int vobsub_read_header(AVFormatContext *s)
  607. {
  608. int i, ret = 0, header_parsed = 0, langidx = 0;
  609. MpegDemuxContext *vobsub = s->priv_data;
  610. char *sub_name = NULL;
  611. size_t fname_len;
  612. char *ext, *header_str;
  613. AVBPrint header;
  614. int64_t delay = 0;
  615. AVStream *st = NULL;
  616. int stream_id = -1;
  617. char id[64] = {0};
  618. char alt[MAX_LINE_SIZE] = {0};
  619. sub_name = av_strdup(s->filename);
  620. fname_len = strlen(sub_name);
  621. ext = sub_name - 3 + fname_len;
  622. if (fname_len < 4 || *(ext - 1) != '.') {
  623. av_log(s, AV_LOG_ERROR, "The input index filename is too short "
  624. "to guess the associated .SUB file\n");
  625. ret = AVERROR_INVALIDDATA;
  626. goto end;
  627. }
  628. memcpy(ext, !strncmp(ext, "IDX", 3) ? "SUB" : "sub", 3);
  629. av_log(s, AV_LOG_VERBOSE, "IDX/SUB: %s -> %s\n", s->filename, sub_name);
  630. ret = avformat_open_input(&vobsub->sub_ctx, sub_name, &ff_mpegps_demuxer, NULL);
  631. if (ret < 0) {
  632. av_log(s, AV_LOG_ERROR, "Unable to open %s as MPEG subtitles\n", sub_name);
  633. goto end;
  634. }
  635. av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED);
  636. while (!url_feof(s->pb)) {
  637. char line[MAX_LINE_SIZE];
  638. int len = ff_get_line(s->pb, line, sizeof(line));
  639. if (!len)
  640. break;
  641. line[strcspn(line, "\r\n")] = 0;
  642. if (!strncmp(line, "id:", 3)) {
  643. if (sscanf(line, "id: %63[^,], index: %u", id, &stream_id) != 2) {
  644. av_log(s, AV_LOG_WARNING, "Unable to parse index line '%s', "
  645. "assuming 'id: und, index: 0'\n", line);
  646. strcpy(id, "und");
  647. stream_id = 0;
  648. }
  649. if (stream_id >= FF_ARRAY_ELEMS(vobsub->q)) {
  650. av_log(s, AV_LOG_ERROR, "Maximum number of subtitles streams reached\n");
  651. ret = AVERROR(EINVAL);
  652. goto end;
  653. }
  654. header_parsed = 1;
  655. alt[0] = '\0';
  656. /* We do not create the stream immediately to avoid adding empty
  657. * streams. See the following timestamp entry. */
  658. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] id=%s\n", stream_id, id);
  659. } else if (!strncmp(line, "timestamp:", 10)) {
  660. AVPacket *sub;
  661. int hh, mm, ss, ms;
  662. int64_t pos, timestamp;
  663. const char *p = line + 10;
  664. if (stream_id == -1) {
  665. av_log(s, AV_LOG_ERROR, "Timestamp declared before any stream\n");
  666. ret = AVERROR_INVALIDDATA;
  667. goto end;
  668. }
  669. if (!st || st->id != stream_id) {
  670. st = avformat_new_stream(s, NULL);
  671. if (!st) {
  672. ret = AVERROR(ENOMEM);
  673. goto end;
  674. }
  675. st->id = stream_id;
  676. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  677. st->codec->codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  678. avpriv_set_pts_info(st, 64, 1, 1000);
  679. av_dict_set(&st->metadata, "language", id, 0);
  680. if (alt[0])
  681. av_dict_set(&st->metadata, "title", alt, 0);
  682. }
  683. if (sscanf(p, "%02d:%02d:%02d:%03d, filepos: %"SCNx64,
  684. &hh, &mm, &ss, &ms, &pos) != 5) {
  685. av_log(s, AV_LOG_ERROR, "Unable to parse timestamp line '%s', "
  686. "abort parsing\n", line);
  687. ret = AVERROR_INVALIDDATA;
  688. goto end;
  689. }
  690. timestamp = (hh*3600LL + mm*60LL + ss) * 1000LL + ms + delay;
  691. timestamp = av_rescale_q(timestamp, av_make_q(1, 1000), st->time_base);
  692. sub = ff_subtitles_queue_insert(&vobsub->q[s->nb_streams - 1], "", 0, 0);
  693. if (!sub) {
  694. ret = AVERROR(ENOMEM);
  695. goto end;
  696. }
  697. sub->pos = pos;
  698. sub->pts = timestamp;
  699. sub->stream_index = s->nb_streams - 1;
  700. } else if (!strncmp(line, "alt:", 4)) {
  701. const char *p = line + 4;
  702. while (*p == ' ')
  703. p++;
  704. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] name=%s\n", st->id, p);
  705. av_strlcpy(alt, p, sizeof(alt));
  706. header_parsed = 1;
  707. } else if (!strncmp(line, "delay:", 6)) {
  708. int sign = 1, hh = 0, mm = 0, ss = 0, ms = 0;
  709. const char *p = line + 6;
  710. while (*p == ' ')
  711. p++;
  712. if (*p == '-' || *p == '+') {
  713. sign = *p == '-' ? -1 : 1;
  714. p++;
  715. }
  716. sscanf(p, "%d:%d:%d:%d", &hh, &mm, &ss, &ms);
  717. delay = ((hh*3600LL + mm*60LL + ss) * 1000LL + ms) * sign;
  718. } else if (!strncmp(line, "langidx:", 8)) {
  719. const char *p = line + 8;
  720. if (sscanf(p, "%d", &langidx) != 1)
  721. av_log(s, AV_LOG_ERROR, "Invalid langidx specified\n");
  722. } else if (!header_parsed) {
  723. if (line[0] && line[0] != '#')
  724. av_bprintf(&header, "%s\n", line);
  725. }
  726. }
  727. if (langidx < s->nb_streams)
  728. s->streams[langidx]->disposition |= AV_DISPOSITION_DEFAULT;
  729. for (i = 0; i < s->nb_streams; i++) {
  730. vobsub->q[i].sort = SUB_SORT_POS_TS;
  731. ff_subtitles_queue_finalize(&vobsub->q[i]);
  732. }
  733. if (!av_bprint_is_complete(&header)) {
  734. av_bprint_finalize(&header, NULL);
  735. ret = AVERROR(ENOMEM);
  736. goto end;
  737. }
  738. av_bprint_finalize(&header, &header_str);
  739. for (i = 0; i < s->nb_streams; i++) {
  740. AVStream *sub_st = s->streams[i];
  741. sub_st->codec->extradata = av_strdup(header_str);
  742. sub_st->codec->extradata_size = header.len;
  743. }
  744. av_free(header_str);
  745. end:
  746. av_free(sub_name);
  747. return ret;
  748. }
  749. static int vobsub_read_packet(AVFormatContext *s, AVPacket *pkt)
  750. {
  751. MpegDemuxContext *vobsub = s->priv_data;
  752. FFDemuxSubtitlesQueue *q;
  753. AVIOContext *pb = vobsub->sub_ctx->pb;
  754. int ret, psize, total_read = 0, i;
  755. AVPacket idx_pkt;
  756. int64_t min_ts = INT64_MAX;
  757. int sid = 0;
  758. for (i = 0; i < s->nb_streams; i++) {
  759. FFDemuxSubtitlesQueue *tmpq = &vobsub->q[i];
  760. int64_t ts;
  761. av_assert0(tmpq->nb_subs);
  762. ts = tmpq->subs[tmpq->current_sub_idx].pts;
  763. if (ts < min_ts) {
  764. min_ts = ts;
  765. sid = i;
  766. }
  767. }
  768. q = &vobsub->q[sid];
  769. ret = ff_subtitles_queue_read_packet(q, &idx_pkt);
  770. if (ret < 0)
  771. return ret;
  772. /* compute maximum packet size using the next packet position. This is
  773. * useful when the len in the header is non-sense */
  774. if (q->current_sub_idx < q->nb_subs) {
  775. psize = q->subs[q->current_sub_idx].pos - idx_pkt.pos;
  776. } else {
  777. int64_t fsize = avio_size(pb);
  778. psize = fsize < 0 ? 0xffff : fsize - idx_pkt.pos;
  779. }
  780. avio_seek(pb, idx_pkt.pos, SEEK_SET);
  781. av_init_packet(pkt);
  782. pkt->size = 0;
  783. pkt->data = NULL;
  784. do {
  785. int n, to_read, startcode;
  786. int64_t pts, dts;
  787. int64_t old_pos = avio_tell(pb), new_pos;
  788. int pkt_size;
  789. ret = mpegps_read_pes_header(vobsub->sub_ctx, NULL, &startcode, &pts, &dts);
  790. if (ret < 0) {
  791. if (pkt->size) // raise packet even if incomplete
  792. break;
  793. goto fail;
  794. }
  795. to_read = ret & 0xffff;
  796. new_pos = avio_tell(pb);
  797. pkt_size = ret + (new_pos - old_pos);
  798. /* this prevents reads above the current packet */
  799. if (total_read + pkt_size > psize)
  800. break;
  801. total_read += pkt_size;
  802. /* the current chunk doesn't match the stream index (unlikely) */
  803. if ((startcode & 0x1f) != idx_pkt.stream_index)
  804. break;
  805. ret = av_grow_packet(pkt, to_read);
  806. if (ret < 0)
  807. goto fail;
  808. n = avio_read(pb, pkt->data + (pkt->size - to_read), to_read);
  809. if (n < to_read)
  810. pkt->size -= to_read - n;
  811. } while (total_read < psize);
  812. pkt->pts = pkt->dts = idx_pkt.pts;
  813. pkt->pos = idx_pkt.pos;
  814. pkt->stream_index = idx_pkt.stream_index;
  815. av_free_packet(&idx_pkt);
  816. return 0;
  817. fail:
  818. av_free_packet(pkt);
  819. av_free_packet(&idx_pkt);
  820. return ret;
  821. }
  822. static int vobsub_read_seek(AVFormatContext *s, int stream_index,
  823. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  824. {
  825. MpegDemuxContext *vobsub = s->priv_data;
  826. /* Rescale requested timestamps based on the first stream (timebase is the
  827. * same for all subtitles stream within a .idx/.sub). Rescaling is done just
  828. * like in avformat_seek_file(). */
  829. if (stream_index == -1 && s->nb_streams != 1) {
  830. int i, ret = 0;
  831. AVRational time_base = s->streams[0]->time_base;
  832. ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
  833. min_ts = av_rescale_rnd(min_ts, time_base.den,
  834. time_base.num * (int64_t)AV_TIME_BASE,
  835. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  836. max_ts = av_rescale_rnd(max_ts, time_base.den,
  837. time_base.num * (int64_t)AV_TIME_BASE,
  838. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  839. for (i = 0; i < s->nb_streams; i++) {
  840. int r = ff_subtitles_queue_seek(&vobsub->q[i], s, stream_index,
  841. min_ts, ts, max_ts, flags);
  842. if (r < 0)
  843. ret = r;
  844. }
  845. return ret;
  846. }
  847. if (stream_index == -1) // only 1 stream
  848. stream_index = 0;
  849. return ff_subtitles_queue_seek(&vobsub->q[stream_index], s, stream_index,
  850. min_ts, ts, max_ts, flags);
  851. }
  852. static int vobsub_read_close(AVFormatContext *s)
  853. {
  854. int i;
  855. MpegDemuxContext *vobsub = s->priv_data;
  856. for (i = 0; i < s->nb_streams; i++)
  857. ff_subtitles_queue_clean(&vobsub->q[i]);
  858. if (vobsub->sub_ctx)
  859. avformat_close_input(&vobsub->sub_ctx);
  860. return 0;
  861. }
  862. AVInputFormat ff_vobsub_demuxer = {
  863. .name = "vobsub",
  864. .long_name = NULL_IF_CONFIG_SMALL("VobSub subtitle format"),
  865. .priv_data_size = sizeof(MpegDemuxContext),
  866. .read_probe = vobsub_probe,
  867. .read_header = vobsub_read_header,
  868. .read_packet = vobsub_read_packet,
  869. .read_seek2 = vobsub_read_seek,
  870. .read_close = vobsub_read_close,
  871. .flags = AVFMT_SHOW_IDS,
  872. .extensions = "idx",
  873. };
  874. #endif