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.

835 lines
26KB

  1. /*
  2. * MPEG1/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 "internal.h"
  23. #include "mpeg.h"
  24. #if CONFIG_VOBSUB_DEMUXER
  25. # include "subtitles.h"
  26. # include "libavutil/bprint.h"
  27. #endif
  28. #undef NDEBUG
  29. #include <assert.h>
  30. /*********************************************/
  31. /* demux code */
  32. #define MAX_SYNC_SIZE 100000
  33. static int check_pes(const uint8_t *p, const uint8_t *end){
  34. int pes1;
  35. int pes2= (p[3] & 0xC0) == 0x80
  36. && (p[4] & 0xC0) != 0x40
  37. &&((p[4] & 0xC0) == 0x00 || (p[4]&0xC0)>>2 == (p[6]&0xF0));
  38. for(p+=3; p<end && *p == 0xFF; p++);
  39. if((*p&0xC0) == 0x40) p+=2;
  40. if((*p&0xF0) == 0x20){
  41. pes1= p[0]&p[2]&p[4]&1;
  42. }else if((*p&0xF0) == 0x30){
  43. pes1= p[0]&p[2]&p[4]&p[5]&p[7]&p[9]&1;
  44. }else
  45. pes1 = *p == 0x0F;
  46. return pes1||pes2;
  47. }
  48. static int check_pack_header(const uint8_t *buf) {
  49. return (buf[1] & 0xC0) == 0x40 || (buf[1] & 0xF0) == 0x20;
  50. }
  51. static int mpegps_probe(AVProbeData *p)
  52. {
  53. uint32_t code= -1;
  54. int sys=0, pspack=0, priv1=0, vid=0, audio=0, invalid=0;
  55. int i;
  56. int score=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= 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) sys++;
  64. else if(code == PACK_START_CODE && pack) pspack++;
  65. else if((code & 0xf0) == VIDEO_ID && pes) vid++;
  66. // skip pes payload to avoid start code emulation for private
  67. // and audio streams
  68. else if((code & 0xe0) == AUDIO_ID && pes) {audio++; i+=len;}
  69. else if(code == PRIVATE_STREAM_1 && pes) {priv1++; i+=len;}
  70. else if(code == 0x1fd && pes) vid++; //VC1
  71. else if((code & 0xf0) == VIDEO_ID && !pes) invalid++;
  72. else if((code & 0xe0) == AUDIO_ID && !pes) invalid++;
  73. else if(code == PRIVATE_STREAM_1 && !pes) invalid++;
  74. }
  75. }
  76. if(vid+audio > invalid+1) /* invalid VDR files nd short PES streams */
  77. score= AVPROBE_SCORE_MAX/4;
  78. if(sys>invalid && sys*9 <= pspack*10)
  79. return (audio > 12 || vid > 3 || pspack > 2) ? AVPROBE_SCORE_MAX/2+2 : AVPROBE_SCORE_MAX/4; // +1 for .mpg
  80. if(pspack > invalid && (priv1+vid+audio)*10 >= pspack*9)
  81. return pspack > 2 ? AVPROBE_SCORE_MAX/2+2 : AVPROBE_SCORE_MAX/4; // +1 for .mpg
  82. if((!!vid ^ !!audio) && (audio > 4 || vid > 1) && !sys && !pspack && p->buf_size>2048 && vid + audio > invalid) /* PES stream */
  83. return (audio > 12 || vid > 3 + 2*invalid) ? AVPROBE_SCORE_MAX/2+2 : AVPROBE_SCORE_MAX/4;
  84. //02-Penguin.flac has sys:0 priv1:0 pspack:0 vid:0 audio:1
  85. //mp3_misidentified_2.mp3 has sys:0 priv1:0 pspack:0 vid:0 audio:6
  86. //Have\ Yourself\ a\ Merry\ Little\ Christmas.mp3 0 0 0 5 0 1 len:21618
  87. return score;
  88. }
  89. typedef struct MpegDemuxContext {
  90. int32_t header_state;
  91. unsigned char psm_es_type[256];
  92. int sofdec;
  93. #if CONFIG_VOBSUB_DEMUXER
  94. AVFormatContext *sub_ctx;
  95. FFDemuxSubtitlesQueue q;
  96. #endif
  97. } MpegDemuxContext;
  98. static int mpegps_read_header(AVFormatContext *s)
  99. {
  100. MpegDemuxContext *m = s->priv_data;
  101. const char *sofdec = "Sofdec";
  102. int v, i = 0;
  103. int64_t last_pos = avio_tell(s->pb);
  104. m->header_state = 0xff;
  105. s->ctx_flags |= AVFMTCTX_NOHEADER;
  106. m->sofdec = -1;
  107. do {
  108. v = avio_r8(s->pb);
  109. m->sofdec++;
  110. } while (v == sofdec[i] && i++ < 6);
  111. m->sofdec = (m->sofdec == 6) ? 1 : 0;
  112. if (!m->sofdec)
  113. avio_seek(s->pb, last_pos, SEEK_SET);
  114. /* no need to do more */
  115. return 0;
  116. }
  117. static int64_t get_pts(AVIOContext *pb, int c)
  118. {
  119. uint8_t buf[5];
  120. buf[0] = c<0 ? avio_r8(pb) : c;
  121. avio_read(pb, buf+1, 4);
  122. return ff_parse_pes_pts(buf);
  123. }
  124. static int find_next_start_code(AVIOContext *pb, int *size_ptr,
  125. int32_t *header_state)
  126. {
  127. unsigned int state, v;
  128. int val, n;
  129. state = *header_state;
  130. n = *size_ptr;
  131. while (n > 0) {
  132. if (url_feof(pb))
  133. break;
  134. v = avio_r8(pb);
  135. n--;
  136. if (state == 0x000001) {
  137. state = ((state << 8) | v) & 0xffffff;
  138. val = state;
  139. goto found;
  140. }
  141. state = ((state << 8) | v) & 0xffffff;
  142. }
  143. val = -1;
  144. found:
  145. *header_state = state;
  146. *size_ptr = n;
  147. return val;
  148. }
  149. /**
  150. * Extract stream types from a program stream map
  151. * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
  152. *
  153. * @return number of bytes occupied by PSM in the bitstream
  154. */
  155. static long mpegps_psm_parse(MpegDemuxContext *m, AVIOContext *pb)
  156. {
  157. int psm_length, ps_info_length, es_map_length;
  158. psm_length = avio_rb16(pb);
  159. avio_r8(pb);
  160. avio_r8(pb);
  161. ps_info_length = avio_rb16(pb);
  162. /* skip program_stream_info */
  163. avio_skip(pb, ps_info_length);
  164. es_map_length = avio_rb16(pb);
  165. /* at least one es available? */
  166. while (es_map_length >= 4){
  167. unsigned char type = avio_r8(pb);
  168. unsigned char es_id = avio_r8(pb);
  169. uint16_t es_info_length = avio_rb16(pb);
  170. /* remember mapping from stream id to stream type */
  171. m->psm_es_type[es_id] = type;
  172. /* skip program_stream_info */
  173. avio_skip(pb, es_info_length);
  174. es_map_length -= 4 + es_info_length;
  175. }
  176. avio_rb32(pb); /* crc32 */
  177. return 2 + psm_length;
  178. }
  179. /* read the next PES header. Return its position in ppos
  180. (if not NULL), and its start code, pts and dts.
  181. */
  182. static int mpegps_read_pes_header(AVFormatContext *s,
  183. int64_t *ppos, int *pstart_code,
  184. int64_t *ppts, int64_t *pdts)
  185. {
  186. MpegDemuxContext *m = s->priv_data;
  187. int len, size, startcode, c, flags, header_len;
  188. int pes_ext, ext2_len, id_ext, skip;
  189. int64_t pts, dts;
  190. int64_t last_sync= avio_tell(s->pb);
  191. error_redo:
  192. avio_seek(s->pb, last_sync, SEEK_SET);
  193. redo:
  194. /* next start code (should be immediately after) */
  195. m->header_state = 0xff;
  196. size = MAX_SYNC_SIZE;
  197. startcode = find_next_start_code(s->pb, &size, &m->header_state);
  198. last_sync = avio_tell(s->pb);
  199. if (startcode < 0){
  200. if(url_feof(s->pb))
  201. return AVERROR_EOF;
  202. //FIXME we should remember header_state
  203. return AVERROR(EAGAIN);
  204. }
  205. if (startcode == PACK_START_CODE)
  206. goto redo;
  207. if (startcode == SYSTEM_HEADER_START_CODE)
  208. goto redo;
  209. if (startcode == PADDING_STREAM) {
  210. avio_skip(s->pb, avio_rb16(s->pb));
  211. goto redo;
  212. }
  213. if (startcode == PRIVATE_STREAM_2) {
  214. len = avio_rb16(s->pb);
  215. if (!m->sofdec) {
  216. while (len-- >= 6) {
  217. if (avio_r8(s->pb) == 'S') {
  218. uint8_t buf[5];
  219. avio_read(s->pb, buf, sizeof(buf));
  220. m->sofdec = !memcmp(buf, "ofdec", 5);
  221. len -= sizeof(buf);
  222. break;
  223. }
  224. }
  225. m->sofdec -= !m->sofdec;
  226. }
  227. avio_skip(s->pb, len);
  228. goto redo;
  229. }
  230. if (startcode == PROGRAM_STREAM_MAP) {
  231. mpegps_psm_parse(m, s->pb);
  232. goto redo;
  233. }
  234. /* find matching stream */
  235. if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
  236. (startcode >= 0x1e0 && startcode <= 0x1ef) ||
  237. (startcode == 0x1bd) || (startcode == 0x1fd)))
  238. goto redo;
  239. if (ppos) {
  240. *ppos = avio_tell(s->pb) - 4;
  241. }
  242. len = avio_rb16(s->pb);
  243. pts =
  244. dts = AV_NOPTS_VALUE;
  245. /* stuffing */
  246. for(;;) {
  247. if (len < 1)
  248. goto error_redo;
  249. c = avio_r8(s->pb);
  250. len--;
  251. /* XXX: for mpeg1, should test only bit 7 */
  252. if (c != 0xff)
  253. break;
  254. }
  255. if ((c & 0xc0) == 0x40) {
  256. /* buffer scale & size */
  257. avio_r8(s->pb);
  258. c = avio_r8(s->pb);
  259. len -= 2;
  260. }
  261. if ((c & 0xe0) == 0x20) {
  262. dts = pts = get_pts(s->pb, c);
  263. len -= 4;
  264. if (c & 0x10){
  265. dts = get_pts(s->pb, -1);
  266. len -= 5;
  267. }
  268. } else if ((c & 0xc0) == 0x80) {
  269. /* mpeg 2 PES */
  270. flags = avio_r8(s->pb);
  271. header_len = avio_r8(s->pb);
  272. len -= 2;
  273. if (header_len > len)
  274. goto error_redo;
  275. len -= header_len;
  276. if (flags & 0x80) {
  277. dts = pts = get_pts(s->pb, -1);
  278. header_len -= 5;
  279. if (flags & 0x40) {
  280. dts = get_pts(s->pb, -1);
  281. header_len -= 5;
  282. }
  283. }
  284. if (flags & 0x3f && header_len == 0){
  285. flags &= 0xC0;
  286. av_log(s, AV_LOG_WARNING, "Further flags set but no bytes left\n");
  287. }
  288. if (flags & 0x01) { /* PES extension */
  289. pes_ext = avio_r8(s->pb);
  290. header_len--;
  291. /* Skip PES private data, program packet sequence counter and P-STD buffer */
  292. skip = (pes_ext >> 4) & 0xb;
  293. skip += skip & 0x9;
  294. if (pes_ext & 0x40 || skip > header_len){
  295. av_log(s, AV_LOG_WARNING, "pes_ext %X is invalid\n", pes_ext);
  296. pes_ext=skip=0;
  297. }
  298. avio_skip(s->pb, skip);
  299. header_len -= skip;
  300. if (pes_ext & 0x01) { /* PES extension 2 */
  301. ext2_len = avio_r8(s->pb);
  302. header_len--;
  303. if ((ext2_len & 0x7f) > 0) {
  304. id_ext = avio_r8(s->pb);
  305. if ((id_ext & 0x80) == 0)
  306. startcode = ((startcode & 0xff) << 8) | id_ext;
  307. header_len--;
  308. }
  309. }
  310. }
  311. if(header_len < 0)
  312. goto error_redo;
  313. avio_skip(s->pb, header_len);
  314. }
  315. else if( c!= 0xf )
  316. goto redo;
  317. if (startcode == PRIVATE_STREAM_1) {
  318. startcode = avio_r8(s->pb);
  319. len--;
  320. }
  321. if(len<0)
  322. goto error_redo;
  323. if(dts != AV_NOPTS_VALUE && ppos){
  324. int i;
  325. for(i=0; i<s->nb_streams; i++){
  326. if(startcode == s->streams[i]->id &&
  327. s->pb->seekable /* index useless on streams anyway */) {
  328. ff_reduce_index(s, i);
  329. av_add_index_entry(s->streams[i], *ppos, dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  330. }
  331. }
  332. }
  333. *pstart_code = startcode;
  334. *ppts = pts;
  335. *pdts = dts;
  336. return len;
  337. }
  338. static int mpegps_read_packet(AVFormatContext *s,
  339. AVPacket *pkt)
  340. {
  341. MpegDemuxContext *m = s->priv_data;
  342. AVStream *st;
  343. int len, startcode, i, es_type, ret;
  344. int lpcm_header_len = -1; //Init to supress warning
  345. int request_probe= 0;
  346. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  347. enum AVMediaType type;
  348. int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
  349. redo:
  350. len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
  351. if (len < 0)
  352. return len;
  353. if (startcode >= 0x80 && startcode <= 0xcf) {
  354. if(len < 4)
  355. goto skip;
  356. /* audio: skip header */
  357. avio_r8(s->pb);
  358. lpcm_header_len = avio_rb16(s->pb);
  359. len -= 3;
  360. if (startcode >= 0xb0 && startcode <= 0xbf) {
  361. /* MLP/TrueHD audio has a 4-byte header */
  362. avio_r8(s->pb);
  363. len--;
  364. }
  365. }
  366. /* now find stream */
  367. for(i=0;i<s->nb_streams;i++) {
  368. st = s->streams[i];
  369. if (st->id == startcode)
  370. goto found;
  371. }
  372. es_type = m->psm_es_type[startcode & 0xff];
  373. if(es_type == STREAM_TYPE_VIDEO_MPEG1){
  374. codec_id = AV_CODEC_ID_MPEG2VIDEO;
  375. type = AVMEDIA_TYPE_VIDEO;
  376. } else if(es_type == STREAM_TYPE_VIDEO_MPEG2){
  377. codec_id = AV_CODEC_ID_MPEG2VIDEO;
  378. type = AVMEDIA_TYPE_VIDEO;
  379. } else if(es_type == STREAM_TYPE_AUDIO_MPEG1 ||
  380. es_type == STREAM_TYPE_AUDIO_MPEG2){
  381. codec_id = AV_CODEC_ID_MP3;
  382. type = AVMEDIA_TYPE_AUDIO;
  383. } else if(es_type == STREAM_TYPE_AUDIO_AAC){
  384. codec_id = AV_CODEC_ID_AAC;
  385. type = AVMEDIA_TYPE_AUDIO;
  386. } else if(es_type == STREAM_TYPE_VIDEO_MPEG4){
  387. codec_id = AV_CODEC_ID_MPEG4;
  388. type = AVMEDIA_TYPE_VIDEO;
  389. } else if(es_type == STREAM_TYPE_VIDEO_H264){
  390. codec_id = AV_CODEC_ID_H264;
  391. type = AVMEDIA_TYPE_VIDEO;
  392. } else if(es_type == STREAM_TYPE_AUDIO_AC3){
  393. codec_id = AV_CODEC_ID_AC3;
  394. type = AVMEDIA_TYPE_AUDIO;
  395. } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
  396. static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
  397. unsigned char buf[8];
  398. avio_read(s->pb, buf, 8);
  399. avio_seek(s->pb, -8, SEEK_CUR);
  400. if(!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1))
  401. codec_id = AV_CODEC_ID_CAVS;
  402. else
  403. request_probe= 1;
  404. type = AVMEDIA_TYPE_VIDEO;
  405. } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
  406. type = AVMEDIA_TYPE_AUDIO;
  407. codec_id = m->sofdec > 0 ? AV_CODEC_ID_ADPCM_ADX : AV_CODEC_ID_MP2;
  408. } else if (startcode >= 0x80 && startcode <= 0x87) {
  409. type = AVMEDIA_TYPE_AUDIO;
  410. codec_id = AV_CODEC_ID_AC3;
  411. } else if ( ( startcode >= 0x88 && startcode <= 0x8f)
  412. ||( startcode >= 0x98 && startcode <= 0x9f)) {
  413. /* 0x90 - 0x97 is reserved for SDDS in DVD specs */
  414. type = AVMEDIA_TYPE_AUDIO;
  415. codec_id = AV_CODEC_ID_DTS;
  416. } else if (startcode >= 0xa0 && startcode <= 0xaf) {
  417. type = AVMEDIA_TYPE_AUDIO;
  418. if(lpcm_header_len == 6) {
  419. codec_id = AV_CODEC_ID_MLP;
  420. } else {
  421. /* 16 bit form will be handled as AV_CODEC_ID_PCM_S16BE */
  422. codec_id = AV_CODEC_ID_PCM_DVD;
  423. }
  424. } else if (startcode >= 0xb0 && startcode <= 0xbf) {
  425. type = AVMEDIA_TYPE_AUDIO;
  426. codec_id = AV_CODEC_ID_TRUEHD;
  427. } else if (startcode >= 0xc0 && startcode <= 0xcf) {
  428. /* Used for both AC-3 and E-AC-3 in EVOB files */
  429. type = AVMEDIA_TYPE_AUDIO;
  430. codec_id = AV_CODEC_ID_AC3;
  431. } else if (startcode >= 0x20 && startcode <= 0x3f) {
  432. type = AVMEDIA_TYPE_SUBTITLE;
  433. codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  434. } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) {
  435. type = AVMEDIA_TYPE_VIDEO;
  436. codec_id = AV_CODEC_ID_VC1;
  437. } else {
  438. skip:
  439. /* skip packet */
  440. avio_skip(s->pb, len);
  441. goto redo;
  442. }
  443. /* no stream found: add a new stream */
  444. st = avformat_new_stream(s, NULL);
  445. if (!st)
  446. goto skip;
  447. st->id = startcode;
  448. st->codec->codec_type = type;
  449. st->codec->codec_id = codec_id;
  450. st->request_probe = request_probe;
  451. if (codec_id != AV_CODEC_ID_PCM_S16BE)
  452. st->need_parsing = AVSTREAM_PARSE_FULL;
  453. found:
  454. if(st->discard >= AVDISCARD_ALL)
  455. goto skip;
  456. if (startcode >= 0xa0 && startcode <= 0xaf) {
  457. if (lpcm_header_len == 6 && st->codec->codec_id == AV_CODEC_ID_MLP) {
  458. if (len < 6)
  459. goto skip;
  460. avio_skip(s->pb, 6);
  461. len -=6;
  462. } else {
  463. int b1, freq;
  464. /* for LPCM, we just skip the header and consider it is raw
  465. audio data */
  466. if (len <= 3)
  467. goto skip;
  468. avio_r8(s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
  469. b1 = avio_r8(s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
  470. avio_r8(s->pb); /* dynamic range control (0x80 = off) */
  471. len -= 3;
  472. freq = (b1 >> 4) & 3;
  473. st->codec->sample_rate = lpcm_freq_tab[freq];
  474. st->codec->channels = 1 + (b1 & 7);
  475. st->codec->bits_per_coded_sample = 16 + ((b1 >> 6) & 3) * 4;
  476. st->codec->bit_rate = st->codec->channels *
  477. st->codec->sample_rate *
  478. st->codec->bits_per_coded_sample;
  479. if (st->codec->bits_per_coded_sample == 16)
  480. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  481. else if (st->codec->bits_per_coded_sample == 28)
  482. return AVERROR(EINVAL);
  483. }
  484. }
  485. ret = av_get_packet(s->pb, pkt, len);
  486. pkt->pts = pts;
  487. pkt->dts = dts;
  488. pkt->pos = dummy_pos;
  489. pkt->stream_index = st->index;
  490. av_dlog(s, "%d: pts=%0.3f dts=%0.3f size=%d\n",
  491. pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0,
  492. pkt->size);
  493. return (ret < 0) ? ret : 0;
  494. }
  495. static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
  496. int64_t *ppos, int64_t pos_limit)
  497. {
  498. int len, startcode;
  499. int64_t pos, pts, dts;
  500. pos = *ppos;
  501. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  502. return AV_NOPTS_VALUE;
  503. for(;;) {
  504. len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
  505. if (len < 0) {
  506. av_dlog(s, "none (ret=%d)\n", len);
  507. return AV_NOPTS_VALUE;
  508. }
  509. if (startcode == s->streams[stream_index]->id &&
  510. dts != AV_NOPTS_VALUE) {
  511. break;
  512. }
  513. avio_skip(s->pb, len);
  514. }
  515. av_dlog(s, "pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n",
  516. pos, dts, dts / 90000.0);
  517. *ppos = pos;
  518. return dts;
  519. }
  520. AVInputFormat ff_mpegps_demuxer = {
  521. .name = "mpeg",
  522. .long_name = NULL_IF_CONFIG_SMALL("MPEG-PS (MPEG-2 Program Stream)"),
  523. .priv_data_size = sizeof(MpegDemuxContext),
  524. .read_probe = mpegps_probe,
  525. .read_header = mpegps_read_header,
  526. .read_packet = mpegps_read_packet,
  527. .read_timestamp = mpegps_read_dts,
  528. .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
  529. };
  530. #if CONFIG_VOBSUB_DEMUXER
  531. #define REF_STRING "# VobSub index file,"
  532. static int vobsub_probe(AVProbeData *p)
  533. {
  534. if (!strncmp(p->buf, REF_STRING, sizeof(REF_STRING) - 1))
  535. return AVPROBE_SCORE_MAX;
  536. return 0;
  537. }
  538. static int vobsub_read_header(AVFormatContext *s)
  539. {
  540. int i, ret = 0, header_parsed = 0, langidx = 0;
  541. MpegDemuxContext *vobsub = s->priv_data;
  542. char *sub_name = NULL;
  543. size_t fname_len;
  544. char *ext, *header_str;
  545. AVBPrint header;
  546. int64_t delay = 0;
  547. AVStream *st = NULL;
  548. sub_name = av_strdup(s->filename);
  549. fname_len = strlen(sub_name);
  550. ext = sub_name - 3 + fname_len;
  551. if (fname_len < 4 || *(ext - 1) != '.') {
  552. av_log(s, AV_LOG_ERROR, "The input index filename is too short "
  553. "to guess the associated .SUB file\n");
  554. ret = AVERROR_INVALIDDATA;
  555. goto end;
  556. }
  557. memcpy(ext, !strncmp(ext, "IDX", 3) ? "SUB" : "sub", 3);
  558. av_log(s, AV_LOG_VERBOSE, "IDX/SUB: %s -> %s\n", s->filename, sub_name);
  559. ret = avformat_open_input(&vobsub->sub_ctx, sub_name, &ff_mpegps_demuxer, NULL);
  560. if (ret < 0) {
  561. av_log(s, AV_LOG_ERROR, "Unable to open %s as MPEG subtitles\n", sub_name);
  562. goto end;
  563. }
  564. av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED);
  565. while (!url_feof(s->pb)) {
  566. char line[2048];
  567. int len = ff_get_line(s->pb, line, sizeof(line));
  568. if (!len)
  569. break;
  570. line[strcspn(line, "\r\n")] = 0;
  571. if (!strncmp(line, "id:", 3)) {
  572. int n, stream_id = 0;
  573. char id[64] = {0};
  574. n = sscanf(line, "id: %63[^,], index: %u", id, &stream_id);
  575. if (n != 2) {
  576. av_log(s, AV_LOG_WARNING, "Unable to parse index line '%s', "
  577. "assuming 'id: und, index: 0'\n", line);
  578. strcpy(id, "und");
  579. stream_id = 0;
  580. }
  581. st = avformat_new_stream(s, NULL);
  582. if (!st) {
  583. ret = AVERROR(ENOMEM);
  584. goto end;
  585. }
  586. st->id = stream_id;
  587. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  588. st->codec->codec_id = AV_CODEC_ID_DVD_SUBTITLE;
  589. av_dict_set(&st->metadata, "language", id, 0);
  590. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] id=%s\n", stream_id, id);
  591. header_parsed = 1;
  592. } else if (st && !strncmp(line, "timestamp:", 10)) {
  593. AVPacket *sub;
  594. int hh, mm, ss, ms;
  595. int64_t pos, timestamp;
  596. const char *p = line + 10;
  597. if (sscanf(p, "%02d:%02d:%02d:%03d, filepos: %"PRIx64,
  598. &hh, &mm, &ss, &ms, &pos) != 5) {
  599. av_log(s, AV_LOG_ERROR, "Unable to parse timestamp line '%s', "
  600. "abort parsing\n", line);
  601. break;
  602. }
  603. timestamp = (hh*3600LL + mm*60LL + ss) * 1000LL + ms + delay;
  604. timestamp = av_rescale_q(timestamp, (AVRational){1,1000}, st->time_base);
  605. sub = ff_subtitles_queue_insert(&vobsub->q, "", 0, 0);
  606. if (!sub) {
  607. ret = AVERROR(ENOMEM);
  608. goto end;
  609. }
  610. sub->pos = pos;
  611. sub->pts = timestamp;
  612. sub->stream_index = s->nb_streams - 1;
  613. } else if (st && !strncmp(line, "alt:", 4)) {
  614. const char *p = line + 4;
  615. while (*p == ' ')
  616. p++;
  617. av_dict_set(&st->metadata, "title", p, 0);
  618. av_log(s, AV_LOG_DEBUG, "IDX stream[%d] name=%s\n", st->id, p);
  619. header_parsed = 1;
  620. } else if (!strncmp(line, "delay:", 6)) {
  621. int sign = 1, hh = 0, mm = 0, ss = 0, ms = 0;
  622. const char *p = line + 6;
  623. while (*p == ' ')
  624. p++;
  625. if (*p == '-' || *p == '+') {
  626. sign = *p == '-' ? -1 : 1;
  627. p++;
  628. }
  629. sscanf(p, "%d:%d:%d:%d", &hh, &mm, &ss, &ms);
  630. delay = ((hh*3600LL + mm*60LL + ss) * 1000LL + ms) * sign;
  631. } else if (!strncmp(line, "langidx:", 8)) {
  632. const char *p = line + 8;
  633. if (sscanf(p, "%d", &langidx) != 1)
  634. av_log(s, AV_LOG_ERROR, "Invalid langidx specified\n");
  635. } else if (!header_parsed) {
  636. if (line[0] && line[0] != '#')
  637. av_bprintf(&header, "%s\n", line);
  638. }
  639. }
  640. if (langidx < s->nb_streams)
  641. s->streams[langidx]->disposition |= AV_DISPOSITION_DEFAULT;
  642. ff_subtitles_queue_finalize(&vobsub->q);
  643. if (!av_bprint_is_complete(&header)) {
  644. av_bprint_finalize(&header, NULL);
  645. ret = AVERROR(ENOMEM);
  646. goto end;
  647. }
  648. av_bprint_finalize(&header, &header_str);
  649. for (i = 0; i < s->nb_streams; i++) {
  650. AVStream *sub_st = s->streams[i];
  651. sub_st->codec->extradata = av_strdup(header_str);
  652. sub_st->codec->extradata_size = header.len;
  653. }
  654. av_free(header_str);
  655. end:
  656. av_free(sub_name);
  657. return ret;
  658. }
  659. static int vobsub_read_packet(AVFormatContext *s, AVPacket *pkt)
  660. {
  661. MpegDemuxContext *vobsub = s->priv_data;
  662. FFDemuxSubtitlesQueue *q = &vobsub->q;
  663. AVIOContext *pb = vobsub->sub_ctx->pb;
  664. int ret, psize, len16 = -1;
  665. AVPacket idx_pkt;
  666. ret = ff_subtitles_queue_read_packet(q, &idx_pkt);
  667. if (ret < 0)
  668. return ret;
  669. /* compute maximum packet size using the next packet position. This is
  670. * useful when the len in the header is non-sense */
  671. if (q->current_sub_idx < q->nb_subs) {
  672. psize = q->subs[q->current_sub_idx].pos - idx_pkt.pos;
  673. } else {
  674. int64_t fsize = avio_size(pb);
  675. psize = fsize < 0 ? 0xffff : fsize - idx_pkt.pos;
  676. }
  677. avio_seek(pb, idx_pkt.pos, SEEK_SET);
  678. av_init_packet(pkt);
  679. pkt->size = 0;
  680. pkt->data = NULL;
  681. do {
  682. int n, to_read, startcode;
  683. int64_t pts, dts;
  684. ret = mpegps_read_pes_header(vobsub->sub_ctx, NULL, &startcode, &pts, &dts);
  685. if (ret < 0)
  686. return ret;
  687. to_read = ret & 0xffff;
  688. /* this prevents reads above the current packet */
  689. if (pkt->size + to_read > psize)
  690. break;
  691. /* if the len is computed, we check for overread */
  692. if (len16 != -1 && pkt->size + to_read > len16)
  693. break;
  694. /* the current chunk doesn't match the stream index (unlikely) */
  695. if ((startcode & 0x1f) != idx_pkt.stream_index)
  696. break;
  697. ret = av_grow_packet(pkt, to_read);
  698. if (ret < 0)
  699. return ret;
  700. n = avio_read(pb, pkt->data + (pkt->size - to_read), to_read);
  701. if (n < to_read)
  702. pkt->size -= to_read - n;
  703. /* first chunk contains the total len of the packet to raise */
  704. if (len16 == -1 && n > 2)
  705. len16 = AV_RB16(pkt->data);
  706. } while (len16 != -1 && pkt->size != len16);
  707. pkt->pts = pkt->dts = idx_pkt.pts;
  708. pkt->pos = idx_pkt.pos;
  709. pkt->stream_index = idx_pkt.stream_index;
  710. return 0;
  711. }
  712. static int vobsub_read_seek(AVFormatContext *s, int stream_index,
  713. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  714. {
  715. MpegDemuxContext *vobsub = s->priv_data;
  716. return ff_subtitles_queue_seek(&vobsub->q, s, stream_index,
  717. min_ts, ts, max_ts, flags);
  718. }
  719. static int vobsub_read_close(AVFormatContext *s)
  720. {
  721. MpegDemuxContext *vobsub = s->priv_data;
  722. ff_subtitles_queue_clean(&vobsub->q);
  723. if (vobsub->sub_ctx)
  724. avformat_close_input(&vobsub->sub_ctx);
  725. return 0;
  726. }
  727. AVInputFormat ff_vobsub_demuxer = {
  728. .name = "vobsub",
  729. .long_name = NULL_IF_CONFIG_SMALL("VobSub subtitle format"),
  730. .priv_data_size = sizeof(MpegDemuxContext),
  731. .read_probe = vobsub_probe,
  732. .read_header = vobsub_read_header,
  733. .read_packet = vobsub_read_packet,
  734. .read_seek2 = vobsub_read_seek,
  735. .read_close = vobsub_read_close,
  736. .flags = AVFMT_SHOW_IDS,
  737. .extensions = "idx",
  738. };
  739. #endif