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.

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