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.

1056 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. if (startcode == 0x0b && avio_r8(s->pb) == 0x77) {
  403. startcode = 0x80;
  404. m->raw_ac3 = 1;
  405. avio_skip(s->pb, -2);
  406. } else {
  407. m->raw_ac3 = 0;
  408. avio_skip(s->pb, -1);
  409. len--;
  410. }
  411. }
  412. if (len < 0)
  413. goto error_redo;
  414. if (dts != AV_NOPTS_VALUE && ppos) {
  415. int i;
  416. for (i = 0; i < s->nb_streams; i++) {
  417. if (startcode == s->streams[i]->id &&
  418. (s->pb->seekable & AVIO_SEEKABLE_NORMAL) /* index useless on streams anyway */) {
  419. ff_reduce_index(s, i);
  420. av_add_index_entry(s->streams[i], *ppos, dts, 0, 0,
  421. AVINDEX_KEYFRAME /* FIXME keyframe? */);
  422. }
  423. }
  424. }
  425. *pstart_code = startcode;
  426. *ppts = pts;
  427. *pdts = dts;
  428. return len;
  429. }
  430. static int mpegps_read_packet(AVFormatContext *s,
  431. AVPacket *pkt)
  432. {
  433. MpegDemuxContext *m = s->priv_data;
  434. AVStream *st;
  435. int len, startcode, i, es_type, ret;
  436. int lpcm_header_len = -1; //Init to suppress warning
  437. int request_probe= 0;
  438. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  439. enum AVMediaType type;
  440. int64_t pts, dts, dummy_pos; // dummy_pos is needed for the index building to work
  441. redo:
  442. len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
  443. if (len < 0)
  444. return len;
  445. if (startcode >= 0x80 && startcode <= 0xcf) {
  446. if (len < 4)
  447. goto skip;
  448. if (!m->raw_ac3) {
  449. /* audio: skip header */
  450. avio_r8(s->pb);
  451. lpcm_header_len = avio_rb16(s->pb);
  452. len -= 3;
  453. if (startcode >= 0xb0 && startcode <= 0xbf) {
  454. /* MLP/TrueHD audio has a 4-byte header */
  455. avio_r8(s->pb);
  456. len--;
  457. }
  458. }
  459. }
  460. /* now find stream */
  461. for (i = 0; i < s->nb_streams; i++) {
  462. st = s->streams[i];
  463. if (st->id == startcode)
  464. goto found;
  465. }
  466. es_type = m->psm_es_type[startcode & 0xff];
  467. if (es_type == STREAM_TYPE_VIDEO_MPEG1) {
  468. codec_id = AV_CODEC_ID_MPEG2VIDEO;
  469. type = AVMEDIA_TYPE_VIDEO;
  470. } else if (es_type == STREAM_TYPE_VIDEO_MPEG2) {
  471. codec_id = AV_CODEC_ID_MPEG2VIDEO;
  472. type = AVMEDIA_TYPE_VIDEO;
  473. } else if (es_type == STREAM_TYPE_AUDIO_MPEG1 ||
  474. es_type == STREAM_TYPE_AUDIO_MPEG2) {
  475. codec_id = AV_CODEC_ID_MP3;
  476. type = AVMEDIA_TYPE_AUDIO;
  477. } else if (es_type == STREAM_TYPE_AUDIO_AAC) {
  478. codec_id = AV_CODEC_ID_AAC;
  479. type = AVMEDIA_TYPE_AUDIO;
  480. } else if (es_type == STREAM_TYPE_VIDEO_MPEG4) {
  481. codec_id = AV_CODEC_ID_MPEG4;
  482. type = AVMEDIA_TYPE_VIDEO;
  483. } else if (es_type == STREAM_TYPE_VIDEO_H264) {
  484. codec_id = AV_CODEC_ID_H264;
  485. type = AVMEDIA_TYPE_VIDEO;
  486. } else if (es_type == STREAM_TYPE_AUDIO_AC3) {
  487. codec_id = AV_CODEC_ID_AC3;
  488. type = AVMEDIA_TYPE_AUDIO;
  489. } else if (m->imkh_cctv && es_type == 0x91) {
  490. codec_id = AV_CODEC_ID_PCM_MULAW;
  491. type = AVMEDIA_TYPE_AUDIO;
  492. } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
  493. static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
  494. unsigned char buf[8];
  495. avio_read(s->pb, buf, 8);
  496. avio_seek(s->pb, -8, SEEK_CUR);
  497. if (!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1))
  498. codec_id = AV_CODEC_ID_CAVS;
  499. else
  500. request_probe= 1;
  501. type = AVMEDIA_TYPE_VIDEO;
  502. } else if (startcode == PRIVATE_STREAM_2) {
  503. type = AVMEDIA_TYPE_DATA;
  504. codec_id = AV_CODEC_ID_DVD_NAV;
  505. } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
  506. type = AVMEDIA_TYPE_AUDIO;
  507. if (m->sofdec > 0) {
  508. codec_id = AV_CODEC_ID_ADPCM_ADX;
  509. // Auto-detect AC-3
  510. request_probe = 50;
  511. } else if (m->imkh_cctv && startcode == 0x1c0 && len > 80) {
  512. codec_id = AV_CODEC_ID_PCM_ALAW;
  513. request_probe = 50;
  514. } else {
  515. codec_id = AV_CODEC_ID_MP2;
  516. if (m->imkh_cctv)
  517. request_probe = 25;
  518. }
  519. } else if (startcode >= 0x80 && startcode <= 0x87) {
  520. type = AVMEDIA_TYPE_AUDIO;
  521. codec_id = AV_CODEC_ID_AC3;
  522. } else if ((startcode >= 0x88 && startcode <= 0x8f) ||
  523. (startcode >= 0x98 && startcode <= 0x9f)) {
  524. /* 0x90 - 0x97 is reserved for SDDS in DVD specs */
  525. type = AVMEDIA_TYPE_AUDIO;
  526. codec_id = AV_CODEC_ID_DTS;
  527. } else if (startcode >= 0xa0 && startcode <= 0xaf) {
  528. type = AVMEDIA_TYPE_AUDIO;
  529. if (lpcm_header_len >= 6 && startcode == 0xa1) {
  530. codec_id = AV_CODEC_ID_MLP;
  531. } else {
  532. codec_id = AV_CODEC_ID_PCM_DVD;
  533. }
  534. } else if (startcode >= 0xb0 && startcode <= 0xbf) {
  535. type = AVMEDIA_TYPE_AUDIO;
  536. codec_id = AV_CODEC_ID_TRUEHD;
  537. } else if (startcode >= 0xc0 && startcode <= 0xcf) {
  538. /* Used for both AC-3 and E-AC-3 in EVOB files */
  539. type = AVMEDIA_TYPE_AUDIO;
  540. codec_id = AV_CODEC_ID_AC3;
  541. } else if (startcode >= 0x20 && startcode <= 0x3f) {
  542. type = AVMEDIA_TYPE_SUBTITLE;
  543. codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  544. } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) {
  545. type = AVMEDIA_TYPE_VIDEO;
  546. codec_id = AV_CODEC_ID_VC1;
  547. } else {
  548. skip:
  549. /* skip packet */
  550. avio_skip(s->pb, len);
  551. goto redo;
  552. }
  553. /* no stream found: add a new stream */
  554. st = avformat_new_stream(s, NULL);
  555. if (!st)
  556. goto skip;
  557. st->id = startcode;
  558. st->codecpar->codec_type = type;
  559. st->codecpar->codec_id = codec_id;
  560. if ( st->codecpar->codec_id == AV_CODEC_ID_PCM_MULAW
  561. || st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW) {
  562. st->codecpar->channels = 1;
  563. st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
  564. st->codecpar->sample_rate = 8000;
  565. }
  566. st->request_probe = request_probe;
  567. st->need_parsing = AVSTREAM_PARSE_FULL;
  568. found:
  569. if (st->discard >= AVDISCARD_ALL)
  570. goto skip;
  571. if (startcode >= 0xa0 && startcode <= 0xaf) {
  572. if (st->codecpar->codec_id == AV_CODEC_ID_MLP) {
  573. if (len < 6)
  574. goto skip;
  575. avio_skip(s->pb, 6);
  576. len -=6;
  577. }
  578. }
  579. ret = av_get_packet(s->pb, pkt, len);
  580. pkt->pts = pts;
  581. pkt->dts = dts;
  582. pkt->pos = dummy_pos;
  583. pkt->stream_index = st->index;
  584. if (s->debug & FF_FDEBUG_TS)
  585. av_log(s, AV_LOG_TRACE, "%d: pts=%0.3f dts=%0.3f size=%d\n",
  586. pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0,
  587. pkt->size);
  588. return (ret < 0) ? ret : 0;
  589. }
  590. static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
  591. int64_t *ppos, int64_t pos_limit)
  592. {
  593. int len, startcode;
  594. int64_t pos, pts, dts;
  595. pos = *ppos;
  596. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  597. return AV_NOPTS_VALUE;
  598. for (;;) {
  599. len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
  600. if (len < 0) {
  601. if (s->debug & FF_FDEBUG_TS)
  602. av_log(s, AV_LOG_TRACE, "none (ret=%d)\n", len);
  603. return AV_NOPTS_VALUE;
  604. }
  605. if (startcode == s->streams[stream_index]->id &&
  606. dts != AV_NOPTS_VALUE) {
  607. break;
  608. }
  609. avio_skip(s->pb, len);
  610. }
  611. if (s->debug & FF_FDEBUG_TS)
  612. av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n",
  613. pos, dts, dts / 90000.0);
  614. *ppos = pos;
  615. return dts;
  616. }
  617. AVInputFormat ff_mpegps_demuxer = {
  618. .name = "mpeg",
  619. .long_name = NULL_IF_CONFIG_SMALL("MPEG-PS (MPEG-2 Program Stream)"),
  620. .priv_data_size = sizeof(MpegDemuxContext),
  621. .read_probe = mpegps_probe,
  622. .read_header = mpegps_read_header,
  623. .read_packet = mpegps_read_packet,
  624. .read_timestamp = mpegps_read_dts,
  625. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  626. };
  627. #if CONFIG_VOBSUB_DEMUXER
  628. #define REF_STRING "# VobSub index file,"
  629. #define MAX_LINE_SIZE 2048
  630. static int vobsub_probe(AVProbeData *p)
  631. {
  632. if (!strncmp(p->buf, REF_STRING, sizeof(REF_STRING) - 1))
  633. return AVPROBE_SCORE_MAX;
  634. return 0;
  635. }
  636. static int vobsub_read_header(AVFormatContext *s)
  637. {
  638. int i, ret = 0, header_parsed = 0, langidx = 0;
  639. MpegDemuxContext *vobsub = s->priv_data;
  640. size_t fname_len;
  641. char *header_str;
  642. AVBPrint header;
  643. int64_t delay = 0;
  644. AVStream *st = NULL;
  645. int stream_id = -1;
  646. char id[64] = {0};
  647. char alt[MAX_LINE_SIZE] = {0};
  648. AVInputFormat *iformat;
  649. if (!vobsub->sub_name) {
  650. char *ext;
  651. vobsub->sub_name = av_strdup(s->url);
  652. if (!vobsub->sub_name) {
  653. ret = AVERROR(ENOMEM);
  654. goto end;
  655. }
  656. fname_len = strlen(vobsub->sub_name);
  657. ext = vobsub->sub_name - 3 + fname_len;
  658. if (fname_len < 4 || *(ext - 1) != '.') {
  659. av_log(s, AV_LOG_ERROR, "The input index filename is too short "
  660. "to guess the associated .SUB file\n");
  661. ret = AVERROR_INVALIDDATA;
  662. goto end;
  663. }
  664. memcpy(ext, !strncmp(ext, "IDX", 3) ? "SUB" : "sub", 3);
  665. av_log(s, AV_LOG_VERBOSE, "IDX/SUB: %s -> %s\n", s->url, vobsub->sub_name);
  666. }
  667. if (!(iformat = av_find_input_format("mpeg"))) {
  668. ret = AVERROR_DEMUXER_NOT_FOUND;
  669. goto end;
  670. }
  671. vobsub->sub_ctx = avformat_alloc_context();
  672. if (!vobsub->sub_ctx) {
  673. ret = AVERROR(ENOMEM);
  674. goto end;
  675. }
  676. if ((ret = ff_copy_whiteblacklists(vobsub->sub_ctx, s)) < 0)
  677. goto end;
  678. ret = avformat_open_input(&vobsub->sub_ctx, vobsub->sub_name, iformat, NULL);
  679. if (ret < 0) {
  680. av_log(s, AV_LOG_ERROR, "Unable to open %s as MPEG subtitles\n", vobsub->sub_name);
  681. goto end;
  682. }
  683. av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED);
  684. while (!avio_feof(s->pb)) {
  685. char line[MAX_LINE_SIZE];
  686. int len = ff_get_line(s->pb, line, sizeof(line));
  687. if (!len)
  688. break;
  689. line[strcspn(line, "\r\n")] = 0;
  690. if (!strncmp(line, "id:", 3)) {
  691. if (sscanf(line, "id: %63[^,], index: %u", id, &stream_id) != 2) {
  692. av_log(s, AV_LOG_WARNING, "Unable to parse index line '%s', "
  693. "assuming 'id: und, index: 0'\n", line);
  694. strcpy(id, "und");
  695. stream_id = 0;
  696. }
  697. if (stream_id >= FF_ARRAY_ELEMS(vobsub->q)) {
  698. av_log(s, AV_LOG_ERROR, "Maximum number of subtitles streams reached\n");
  699. ret = AVERROR(EINVAL);
  700. goto end;
  701. }
  702. header_parsed = 1;
  703. alt[0] = '\0';
  704. /* We do not create the stream immediately to avoid adding empty
  705. * streams. See the following timestamp entry. */
  706. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] id=%s\n", stream_id, id);
  707. } else if (!strncmp(line, "timestamp:", 10)) {
  708. AVPacket *sub;
  709. int hh, mm, ss, ms;
  710. int64_t pos, timestamp;
  711. const char *p = line + 10;
  712. if (stream_id == -1) {
  713. av_log(s, AV_LOG_ERROR, "Timestamp declared before any stream\n");
  714. ret = AVERROR_INVALIDDATA;
  715. goto end;
  716. }
  717. if (!st || st->id != stream_id) {
  718. st = avformat_new_stream(s, NULL);
  719. if (!st) {
  720. ret = AVERROR(ENOMEM);
  721. goto end;
  722. }
  723. st->id = stream_id;
  724. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  725. st->codecpar->codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  726. avpriv_set_pts_info(st, 64, 1, 1000);
  727. av_dict_set(&st->metadata, "language", id, 0);
  728. if (alt[0])
  729. av_dict_set(&st->metadata, "title", alt, 0);
  730. }
  731. if (sscanf(p, "%02d:%02d:%02d:%03d, filepos: %"SCNx64,
  732. &hh, &mm, &ss, &ms, &pos) != 5) {
  733. av_log(s, AV_LOG_ERROR, "Unable to parse timestamp line '%s', "
  734. "abort parsing\n", line);
  735. ret = AVERROR_INVALIDDATA;
  736. goto end;
  737. }
  738. timestamp = (hh*3600LL + mm*60LL + ss) * 1000LL + ms + delay;
  739. timestamp = av_rescale_q(timestamp, av_make_q(1, 1000), st->time_base);
  740. sub = ff_subtitles_queue_insert(&vobsub->q[s->nb_streams - 1], "", 0, 0);
  741. if (!sub) {
  742. ret = AVERROR(ENOMEM);
  743. goto end;
  744. }
  745. sub->pos = pos;
  746. sub->pts = timestamp;
  747. sub->stream_index = s->nb_streams - 1;
  748. } else if (!strncmp(line, "alt:", 4)) {
  749. const char *p = line + 4;
  750. while (*p == ' ')
  751. p++;
  752. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] name=%s\n", stream_id, p);
  753. av_strlcpy(alt, p, sizeof(alt));
  754. header_parsed = 1;
  755. } else if (!strncmp(line, "delay:", 6)) {
  756. int sign = 1, hh = 0, mm = 0, ss = 0, ms = 0;
  757. const char *p = line + 6;
  758. while (*p == ' ')
  759. p++;
  760. if (*p == '-' || *p == '+') {
  761. sign = *p == '-' ? -1 : 1;
  762. p++;
  763. }
  764. sscanf(p, "%d:%d:%d:%d", &hh, &mm, &ss, &ms);
  765. delay = ((hh*3600LL + mm*60LL + ss) * 1000LL + ms) * sign;
  766. } else if (!strncmp(line, "langidx:", 8)) {
  767. const char *p = line + 8;
  768. if (sscanf(p, "%d", &langidx) != 1)
  769. av_log(s, AV_LOG_ERROR, "Invalid langidx specified\n");
  770. } else if (!header_parsed) {
  771. if (line[0] && line[0] != '#')
  772. av_bprintf(&header, "%s\n", line);
  773. }
  774. }
  775. if (langidx < s->nb_streams)
  776. s->streams[langidx]->disposition |= AV_DISPOSITION_DEFAULT;
  777. for (i = 0; i < s->nb_streams; i++) {
  778. vobsub->q[i].sort = SUB_SORT_POS_TS;
  779. vobsub->q[i].keep_duplicates = 1;
  780. ff_subtitles_queue_finalize(s, &vobsub->q[i]);
  781. }
  782. if (!av_bprint_is_complete(&header)) {
  783. av_bprint_finalize(&header, NULL);
  784. ret = AVERROR(ENOMEM);
  785. goto end;
  786. }
  787. av_bprint_finalize(&header, &header_str);
  788. for (i = 0; i < s->nb_streams; i++) {
  789. AVStream *sub_st = s->streams[i];
  790. sub_st->codecpar->extradata = av_strdup(header_str);
  791. sub_st->codecpar->extradata_size = header.len;
  792. }
  793. av_free(header_str);
  794. end:
  795. return ret;
  796. }
  797. static int vobsub_read_packet(AVFormatContext *s, AVPacket *pkt)
  798. {
  799. MpegDemuxContext *vobsub = s->priv_data;
  800. FFDemuxSubtitlesQueue *q;
  801. AVIOContext *pb = vobsub->sub_ctx->pb;
  802. int ret, psize, total_read = 0, i;
  803. AVPacket idx_pkt = { 0 };
  804. int64_t min_ts = INT64_MAX;
  805. int sid = 0;
  806. for (i = 0; i < s->nb_streams; i++) {
  807. FFDemuxSubtitlesQueue *tmpq = &vobsub->q[i];
  808. int64_t ts;
  809. av_assert0(tmpq->nb_subs);
  810. ts = tmpq->subs[tmpq->current_sub_idx].pts;
  811. if (ts < min_ts) {
  812. min_ts = ts;
  813. sid = i;
  814. }
  815. }
  816. q = &vobsub->q[sid];
  817. ret = ff_subtitles_queue_read_packet(q, &idx_pkt);
  818. if (ret < 0)
  819. return ret;
  820. /* compute maximum packet size using the next packet position. This is
  821. * useful when the len in the header is non-sense */
  822. if (q->current_sub_idx < q->nb_subs) {
  823. psize = q->subs[q->current_sub_idx].pos - idx_pkt.pos;
  824. } else {
  825. int64_t fsize = avio_size(pb);
  826. psize = fsize < 0 ? 0xffff : fsize - idx_pkt.pos;
  827. }
  828. avio_seek(pb, idx_pkt.pos, SEEK_SET);
  829. av_init_packet(pkt);
  830. pkt->size = 0;
  831. pkt->data = NULL;
  832. do {
  833. int n, to_read, startcode;
  834. int64_t pts, dts;
  835. int64_t old_pos = avio_tell(pb), new_pos;
  836. int pkt_size;
  837. ret = mpegps_read_pes_header(vobsub->sub_ctx, NULL, &startcode, &pts, &dts);
  838. if (ret < 0) {
  839. if (pkt->size) // raise packet even if incomplete
  840. break;
  841. goto fail;
  842. }
  843. to_read = ret & 0xffff;
  844. new_pos = avio_tell(pb);
  845. pkt_size = ret + (new_pos - old_pos);
  846. /* this prevents reads above the current packet */
  847. if (total_read + pkt_size > psize)
  848. break;
  849. total_read += pkt_size;
  850. /* the current chunk doesn't match the stream index (unlikely) */
  851. if ((startcode & 0x1f) != s->streams[idx_pkt.stream_index]->id)
  852. break;
  853. ret = av_grow_packet(pkt, to_read);
  854. if (ret < 0)
  855. goto fail;
  856. n = avio_read(pb, pkt->data + (pkt->size - to_read), to_read);
  857. if (n < to_read)
  858. pkt->size -= to_read - n;
  859. } while (total_read < psize);
  860. pkt->pts = pkt->dts = idx_pkt.pts;
  861. pkt->pos = idx_pkt.pos;
  862. pkt->stream_index = idx_pkt.stream_index;
  863. av_packet_unref(&idx_pkt);
  864. return 0;
  865. fail:
  866. av_packet_unref(pkt);
  867. av_packet_unref(&idx_pkt);
  868. return ret;
  869. }
  870. static int vobsub_read_seek(AVFormatContext *s, int stream_index,
  871. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  872. {
  873. MpegDemuxContext *vobsub = s->priv_data;
  874. /* Rescale requested timestamps based on the first stream (timebase is the
  875. * same for all subtitles stream within a .idx/.sub). Rescaling is done just
  876. * like in avformat_seek_file(). */
  877. if (stream_index == -1 && s->nb_streams != 1) {
  878. int i, ret = 0;
  879. AVRational time_base = s->streams[0]->time_base;
  880. ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
  881. min_ts = av_rescale_rnd(min_ts, time_base.den,
  882. time_base.num * (int64_t)AV_TIME_BASE,
  883. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  884. max_ts = av_rescale_rnd(max_ts, time_base.den,
  885. time_base.num * (int64_t)AV_TIME_BASE,
  886. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  887. for (i = 0; i < s->nb_streams; i++) {
  888. int r = ff_subtitles_queue_seek(&vobsub->q[i], s, stream_index,
  889. min_ts, ts, max_ts, flags);
  890. if (r < 0)
  891. ret = r;
  892. }
  893. return ret;
  894. }
  895. if (stream_index == -1) // only 1 stream
  896. stream_index = 0;
  897. return ff_subtitles_queue_seek(&vobsub->q[stream_index], s, stream_index,
  898. min_ts, ts, max_ts, flags);
  899. }
  900. static int vobsub_read_close(AVFormatContext *s)
  901. {
  902. int i;
  903. MpegDemuxContext *vobsub = s->priv_data;
  904. for (i = 0; i < s->nb_streams; i++)
  905. ff_subtitles_queue_clean(&vobsub->q[i]);
  906. if (vobsub->sub_ctx)
  907. avformat_close_input(&vobsub->sub_ctx);
  908. return 0;
  909. }
  910. static const AVOption options[] = {
  911. { "sub_name", "URI for .sub file", offsetof(MpegDemuxContext, sub_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
  912. { NULL }
  913. };
  914. static const AVClass vobsub_demuxer_class = {
  915. .class_name = "vobsub",
  916. .item_name = av_default_item_name,
  917. .option = options,
  918. .version = LIBAVUTIL_VERSION_INT,
  919. };
  920. AVInputFormat ff_vobsub_demuxer = {
  921. .name = "vobsub",
  922. .long_name = NULL_IF_CONFIG_SMALL("VobSub subtitle format"),
  923. .priv_data_size = sizeof(MpegDemuxContext),
  924. .read_probe = vobsub_probe,
  925. .read_header = vobsub_read_header,
  926. .read_packet = vobsub_read_packet,
  927. .read_seek2 = vobsub_read_seek,
  928. .read_close = vobsub_read_close,
  929. .flags = AVFMT_SHOW_IDS,
  930. .extensions = "idx",
  931. .priv_class = &vobsub_demuxer_class,
  932. };
  933. #endif