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.

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