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