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.

1057 lines
34KB

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