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.

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