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.

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