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.

950 lines
31KB

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