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.

1034 lines
33KB

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