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.

1108 lines
36KB

  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 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 "libavutil/bswap.h"
  22. #include "avformat.h"
  23. #include "avi.h"
  24. #include "dv.h"
  25. #include "riff.h"
  26. #undef NDEBUG
  27. #include <assert.h>
  28. //#define DEBUG
  29. //#define DEBUG_SEEK
  30. typedef struct AVIStream {
  31. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  32. (used to compute the pts) */
  33. int remaining;
  34. int packet_size;
  35. int scale;
  36. int rate;
  37. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  38. int64_t cum_len; /* temporary storage (used during seek) */
  39. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  40. int prefix_count;
  41. uint32_t pal[256];
  42. int has_pal;
  43. } AVIStream;
  44. typedef struct {
  45. int64_t riff_end;
  46. int64_t movi_end;
  47. int64_t fsize;
  48. int64_t movi_list;
  49. int64_t last_pkt_pos;
  50. int index_loaded;
  51. int is_odml;
  52. int non_interleaved;
  53. int stream_index;
  54. DVDemuxContext* dv_demux;
  55. } AVIContext;
  56. static const char avi_headers[][8] = {
  57. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  58. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  59. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  60. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  61. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  62. { 0 }
  63. };
  64. static int avi_load_index(AVFormatContext *s);
  65. static int guess_ni_flag(AVFormatContext *s);
  66. #ifdef DEBUG
  67. static void print_tag(const char *str, unsigned int tag, int size)
  68. {
  69. printf("%s: tag=%c%c%c%c size=0x%x\n",
  70. str, tag & 0xff,
  71. (tag >> 8) & 0xff,
  72. (tag >> 16) & 0xff,
  73. (tag >> 24) & 0xff,
  74. size);
  75. }
  76. #endif
  77. static int get_riff(AVIContext *avi, ByteIOContext *pb)
  78. {
  79. char header[8];
  80. int i;
  81. /* check RIFF header */
  82. get_buffer(pb, header, 4);
  83. avi->riff_end = get_le32(pb); /* RIFF chunk size */
  84. avi->riff_end += url_ftell(pb); /* RIFF chunk end */
  85. get_buffer(pb, header+4, 4);
  86. for(i=0; avi_headers[i][0]; i++)
  87. if(!memcmp(header, avi_headers[i], 8))
  88. break;
  89. if(!avi_headers[i][0])
  90. return -1;
  91. if(header[7] == 0x19)
  92. av_log(NULL, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  93. return 0;
  94. }
  95. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  96. AVIContext *avi = s->priv_data;
  97. ByteIOContext *pb = s->pb;
  98. int longs_pre_entry= get_le16(pb);
  99. int index_sub_type = get_byte(pb);
  100. int index_type = get_byte(pb);
  101. int entries_in_use = get_le32(pb);
  102. int chunk_id = get_le32(pb);
  103. int64_t base = get_le64(pb);
  104. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  105. AVStream *st;
  106. AVIStream *ast;
  107. int i;
  108. int64_t last_pos= -1;
  109. int64_t filesize= url_fsize(s->pb);
  110. #ifdef DEBUG_SEEK
  111. av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  112. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  113. #endif
  114. if(stream_id > s->nb_streams || stream_id < 0)
  115. return -1;
  116. st= s->streams[stream_id];
  117. ast = st->priv_data;
  118. if(index_sub_type)
  119. return -1;
  120. get_le32(pb);
  121. if(index_type && longs_pre_entry != 2)
  122. return -1;
  123. if(index_type>1)
  124. return -1;
  125. if(filesize > 0 && base >= filesize){
  126. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  127. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  128. base &= 0xFFFFFFFF;
  129. else
  130. return -1;
  131. }
  132. for(i=0; i<entries_in_use; i++){
  133. if(index_type){
  134. int64_t pos= get_le32(pb) + base - 8;
  135. int len = get_le32(pb);
  136. int key= len >= 0;
  137. len &= 0x7FFFFFFF;
  138. #ifdef DEBUG_SEEK
  139. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  140. #endif
  141. if(last_pos == pos || pos == base - 8)
  142. avi->non_interleaved= 1;
  143. if(last_pos != pos)
  144. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
  145. if(ast->sample_size)
  146. ast->cum_len += len;
  147. else
  148. ast->cum_len ++;
  149. last_pos= pos;
  150. }else{
  151. int64_t offset, pos;
  152. int duration;
  153. offset = get_le64(pb);
  154. get_le32(pb); /* size */
  155. duration = get_le32(pb);
  156. pos = url_ftell(pb);
  157. url_fseek(pb, offset+8, SEEK_SET);
  158. read_braindead_odml_indx(s, frame_num);
  159. frame_num += duration;
  160. url_fseek(pb, pos, SEEK_SET);
  161. }
  162. }
  163. avi->index_loaded=1;
  164. return 0;
  165. }
  166. static void clean_index(AVFormatContext *s){
  167. int i;
  168. int64_t j;
  169. for(i=0; i<s->nb_streams; i++){
  170. AVStream *st = s->streams[i];
  171. AVIStream *ast = st->priv_data;
  172. int n= st->nb_index_entries;
  173. int max= ast->sample_size;
  174. int64_t pos, size, ts;
  175. if(n != 1 || ast->sample_size==0)
  176. continue;
  177. while(max < 1024) max+=max;
  178. pos= st->index_entries[0].pos;
  179. size= st->index_entries[0].size;
  180. ts= st->index_entries[0].timestamp;
  181. for(j=0; j<size; j+=max){
  182. av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  183. }
  184. }
  185. }
  186. static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
  187. {
  188. ByteIOContext *pb = s->pb;
  189. uint8_t value[1024];
  190. int64_t i = url_ftell(pb);
  191. size += (size & 1);
  192. get_strz(pb, value, sizeof(value));
  193. url_fseek(pb, i+size, SEEK_SET);
  194. return av_metadata_set(&s->metadata, (const AVMetadataTag){key, value});
  195. }
  196. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  197. {
  198. AVIContext *avi = s->priv_data;
  199. ByteIOContext *pb = s->pb;
  200. uint32_t tag, tag1, handler;
  201. int codec_type, stream_index, frame_period, bit_rate;
  202. unsigned int size, nb_frames;
  203. int i;
  204. AVStream *st;
  205. AVIStream *ast = NULL;
  206. int avih_width=0, avih_height=0;
  207. int amv_file_format=0;
  208. avi->stream_index= -1;
  209. if (get_riff(avi, pb) < 0)
  210. return -1;
  211. avi->fsize = url_fsize(pb);
  212. if(avi->fsize<=0)
  213. avi->fsize= avi->riff_end;
  214. /* first list tag */
  215. stream_index = -1;
  216. codec_type = -1;
  217. frame_period = 0;
  218. for(;;) {
  219. if (url_feof(pb))
  220. goto fail;
  221. tag = get_le32(pb);
  222. size = get_le32(pb);
  223. #ifdef DEBUG
  224. print_tag("tag", tag, size);
  225. #endif
  226. switch(tag) {
  227. case MKTAG('L', 'I', 'S', 'T'):
  228. /* Ignored, except at start of video packets. */
  229. tag1 = get_le32(pb);
  230. #ifdef DEBUG
  231. print_tag("list", tag1, 0);
  232. #endif
  233. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  234. avi->movi_list = url_ftell(pb) - 4;
  235. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  236. else avi->movi_end = url_fsize(pb);
  237. #ifdef DEBUG
  238. printf("movi end=%"PRIx64"\n", avi->movi_end);
  239. #endif
  240. goto end_of_header;
  241. }
  242. break;
  243. case MKTAG('d', 'm', 'l', 'h'):
  244. avi->is_odml = 1;
  245. url_fskip(pb, size + (size & 1));
  246. break;
  247. case MKTAG('a', 'm', 'v', 'h'):
  248. amv_file_format=1;
  249. case MKTAG('a', 'v', 'i', 'h'):
  250. /* AVI header */
  251. /* using frame_period is bad idea */
  252. frame_period = get_le32(pb);
  253. bit_rate = get_le32(pb) * 8;
  254. get_le32(pb);
  255. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  256. url_fskip(pb, 2 * 4);
  257. get_le32(pb);
  258. get_le32(pb);
  259. avih_width=get_le32(pb);
  260. avih_height=get_le32(pb);
  261. url_fskip(pb, size - 10 * 4);
  262. break;
  263. case MKTAG('s', 't', 'r', 'h'):
  264. /* stream header */
  265. tag1 = get_le32(pb);
  266. handler = get_le32(pb); /* codec tag */
  267. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  268. url_fskip(pb, size - 8);
  269. break;
  270. }else{
  271. stream_index++;
  272. st = av_new_stream(s, stream_index);
  273. if (!st)
  274. goto fail;
  275. ast = av_mallocz(sizeof(AVIStream));
  276. if (!ast)
  277. goto fail;
  278. st->priv_data = ast;
  279. }
  280. if(amv_file_format)
  281. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  282. #ifdef DEBUG
  283. print_tag("strh", tag1, -1);
  284. #endif
  285. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  286. int64_t dv_dur;
  287. /*
  288. * After some consideration -- I don't think we
  289. * have to support anything but DV in type1 AVIs.
  290. */
  291. if (s->nb_streams != 1)
  292. goto fail;
  293. if (handler != MKTAG('d', 'v', 's', 'd') &&
  294. handler != MKTAG('d', 'v', 'h', 'd') &&
  295. handler != MKTAG('d', 'v', 's', 'l'))
  296. goto fail;
  297. ast = s->streams[0]->priv_data;
  298. av_freep(&s->streams[0]->codec->extradata);
  299. av_freep(&s->streams[0]);
  300. s->nb_streams = 0;
  301. if (ENABLE_DV_DEMUXER) {
  302. avi->dv_demux = dv_init_demux(s);
  303. if (!avi->dv_demux)
  304. goto fail;
  305. }
  306. s->streams[0]->priv_data = ast;
  307. url_fskip(pb, 3 * 4);
  308. ast->scale = get_le32(pb);
  309. ast->rate = get_le32(pb);
  310. url_fskip(pb, 4); /* start time */
  311. dv_dur = get_le32(pb);
  312. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  313. dv_dur *= AV_TIME_BASE;
  314. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  315. }
  316. /*
  317. * else, leave duration alone; timing estimation in utils.c
  318. * will make a guess based on bitrate.
  319. */
  320. stream_index = s->nb_streams - 1;
  321. url_fskip(pb, size - 9*4);
  322. break;
  323. }
  324. assert(stream_index < s->nb_streams);
  325. st->codec->stream_codec_tag= handler;
  326. get_le32(pb); /* flags */
  327. get_le16(pb); /* priority */
  328. get_le16(pb); /* language */
  329. get_le32(pb); /* initial frame */
  330. ast->scale = get_le32(pb);
  331. ast->rate = get_le32(pb);
  332. if(!(ast->scale && ast->rate)){
  333. av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
  334. if(frame_period){
  335. ast->rate = 1000000;
  336. ast->scale = frame_period;
  337. }else{
  338. ast->rate = 25;
  339. ast->scale = 1;
  340. }
  341. }
  342. av_set_pts_info(st, 64, ast->scale, ast->rate);
  343. ast->cum_len=get_le32(pb); /* start */
  344. nb_frames = get_le32(pb);
  345. st->start_time = 0;
  346. st->duration = nb_frames;
  347. get_le32(pb); /* buffer size */
  348. get_le32(pb); /* quality */
  349. ast->sample_size = get_le32(pb); /* sample ssize */
  350. ast->cum_len *= FFMAX(1, ast->sample_size);
  351. // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  352. switch(tag1) {
  353. case MKTAG('v', 'i', 'd', 's'):
  354. codec_type = CODEC_TYPE_VIDEO;
  355. ast->sample_size = 0;
  356. break;
  357. case MKTAG('a', 'u', 'd', 's'):
  358. codec_type = CODEC_TYPE_AUDIO;
  359. break;
  360. case MKTAG('t', 'x', 't', 's'):
  361. //FIXME
  362. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  363. break;
  364. case MKTAG('d', 'a', 't', 's'):
  365. codec_type = CODEC_TYPE_DATA;
  366. break;
  367. default:
  368. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  369. goto fail;
  370. }
  371. ast->frame_offset= ast->cum_len;
  372. url_fskip(pb, size - 12 * 4);
  373. break;
  374. case MKTAG('s', 't', 'r', 'f'):
  375. /* stream header */
  376. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  377. url_fskip(pb, size);
  378. } else {
  379. st = s->streams[stream_index];
  380. switch(codec_type) {
  381. case CODEC_TYPE_VIDEO:
  382. if(amv_file_format){
  383. st->codec->width=avih_width;
  384. st->codec->height=avih_height;
  385. st->codec->codec_type = CODEC_TYPE_VIDEO;
  386. st->codec->codec_id = CODEC_ID_AMV;
  387. url_fskip(pb, size);
  388. break;
  389. }
  390. get_le32(pb); /* size */
  391. st->codec->width = get_le32(pb);
  392. st->codec->height = get_le32(pb);
  393. get_le16(pb); /* panes */
  394. st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
  395. tag1 = get_le32(pb);
  396. get_le32(pb); /* ImageSize */
  397. get_le32(pb); /* XPelsPerMeter */
  398. get_le32(pb); /* YPelsPerMeter */
  399. get_le32(pb); /* ClrUsed */
  400. get_le32(pb); /* ClrImportant */
  401. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  402. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  403. st->codec->codec_tag = tag1;
  404. st->codec->codec_id = CODEC_ID_XSUB;
  405. break;
  406. }
  407. if(size > 10*4 && size<(1<<30)){
  408. st->codec->extradata_size= size - 10*4;
  409. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  410. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  411. }
  412. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  413. get_byte(pb);
  414. /* Extract palette from extradata if bpp <= 8. */
  415. /* This code assumes that extradata contains only palette. */
  416. /* This is true for all paletted codecs implemented in FFmpeg. */
  417. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  418. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  419. #ifdef WORDS_BIGENDIAN
  420. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  421. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  422. #else
  423. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  424. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  425. #endif
  426. st->codec->palctrl->palette_changed = 1;
  427. }
  428. #ifdef DEBUG
  429. print_tag("video", tag1, 0);
  430. #endif
  431. st->codec->codec_type = CODEC_TYPE_VIDEO;
  432. st->codec->codec_tag = tag1;
  433. st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
  434. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  435. // url_fskip(pb, size - 5 * 4);
  436. break;
  437. case CODEC_TYPE_AUDIO:
  438. get_wav_header(pb, st->codec, size);
  439. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  440. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  441. ast->sample_size= st->codec->block_align;
  442. }
  443. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  444. url_fskip(pb, 1);
  445. /* Force parsing as several audio frames can be in
  446. * one packet and timestamps refer to packet start. */
  447. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  448. /* ADTS header is in extradata, AAC without header must be
  449. * stored as exact frames. Parser not needed and it will
  450. * fail. */
  451. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  452. st->need_parsing = AVSTREAM_PARSE_NONE;
  453. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  454. * audio in the header but have Axan as stream_code_tag. */
  455. if (st->codec->stream_codec_tag == ff_get_fourcc("Axan")){
  456. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  457. st->codec->codec_tag = 0;
  458. }
  459. if (amv_file_format)
  460. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  461. break;
  462. default:
  463. st->codec->codec_type = CODEC_TYPE_DATA;
  464. st->codec->codec_id= CODEC_ID_NONE;
  465. st->codec->codec_tag= 0;
  466. url_fskip(pb, size);
  467. break;
  468. }
  469. }
  470. break;
  471. case MKTAG('i', 'n', 'd', 'x'):
  472. i= url_ftell(pb);
  473. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  474. read_braindead_odml_indx(s, 0);
  475. }
  476. url_fseek(pb, i+size, SEEK_SET);
  477. break;
  478. case MKTAG('v', 'p', 'r', 'p'):
  479. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  480. AVRational active, active_aspect;
  481. st = s->streams[stream_index];
  482. get_le32(pb);
  483. get_le32(pb);
  484. get_le32(pb);
  485. get_le32(pb);
  486. get_le32(pb);
  487. active_aspect.den= get_le16(pb);
  488. active_aspect.num= get_le16(pb);
  489. active.num = get_le32(pb);
  490. active.den = get_le32(pb);
  491. get_le32(pb); //nbFieldsPerFrame
  492. if(active_aspect.num && active_aspect.den && active.num && active.den){
  493. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  494. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  495. }
  496. size -= 9*4;
  497. }
  498. url_fseek(pb, size, SEEK_CUR);
  499. break;
  500. case MKTAG('I', 'N', 'A', 'M'):
  501. avi_read_tag(s, "Title", size);
  502. break;
  503. case MKTAG('I', 'A', 'R', 'T'):
  504. avi_read_tag(s, "Artist", size);
  505. break;
  506. case MKTAG('I', 'C', 'O', 'P'):
  507. avi_read_tag(s, "Copyright", size);
  508. break;
  509. case MKTAG('I', 'C', 'M', 'T'):
  510. avi_read_tag(s, "Comment", size);
  511. break;
  512. case MKTAG('I', 'G', 'N', 'R'):
  513. avi_read_tag(s, "Genre", size);
  514. break;
  515. case MKTAG('I', 'P', 'R', 'D'):
  516. avi_read_tag(s, "Album", size);
  517. break;
  518. case MKTAG('I', 'P', 'R', 'T'):
  519. avi_read_tag(s, "Track", size);
  520. break;
  521. default:
  522. if(size > 1000000){
  523. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  524. "I will ignore it and try to continue anyway.\n");
  525. avi->movi_list = url_ftell(pb) - 4;
  526. avi->movi_end = url_fsize(pb);
  527. goto end_of_header;
  528. }
  529. /* skip tag */
  530. size += (size & 1);
  531. url_fskip(pb, size);
  532. break;
  533. }
  534. }
  535. end_of_header:
  536. /* check stream number */
  537. if (stream_index != s->nb_streams - 1) {
  538. fail:
  539. return -1;
  540. }
  541. if(!avi->index_loaded && !url_is_streamed(pb))
  542. avi_load_index(s);
  543. avi->index_loaded = 1;
  544. avi->non_interleaved |= guess_ni_flag(s);
  545. if(avi->non_interleaved) {
  546. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  547. clean_index(s);
  548. }
  549. return 0;
  550. }
  551. static int get_stream_idx(int *d){
  552. if( d[0] >= '0' && d[0] <= '9'
  553. && d[1] >= '0' && d[1] <= '9'){
  554. return (d[0] - '0') * 10 + (d[1] - '0');
  555. }else{
  556. return 100; //invalid stream ID
  557. }
  558. }
  559. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  560. {
  561. AVIContext *avi = s->priv_data;
  562. ByteIOContext *pb = s->pb;
  563. int n, d[8], size;
  564. int64_t i, sync;
  565. void* dstr;
  566. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  567. size = dv_get_packet(avi->dv_demux, pkt);
  568. if (size >= 0)
  569. return size;
  570. }
  571. if(avi->non_interleaved){
  572. int best_stream_index = 0;
  573. AVStream *best_st= NULL;
  574. AVIStream *best_ast;
  575. int64_t best_ts= INT64_MAX;
  576. int i;
  577. for(i=0; i<s->nb_streams; i++){
  578. AVStream *st = s->streams[i];
  579. AVIStream *ast = st->priv_data;
  580. int64_t ts= ast->frame_offset;
  581. if(ast->sample_size)
  582. ts /= ast->sample_size;
  583. ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  584. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  585. if(ts < best_ts && st->nb_index_entries){
  586. best_ts= ts;
  587. best_st= st;
  588. best_stream_index= i;
  589. }
  590. }
  591. if(!best_st)
  592. return -1;
  593. best_ast = best_st->priv_data;
  594. best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
  595. if(best_ast->remaining)
  596. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  597. else{
  598. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  599. if(i>=0)
  600. best_ast->frame_offset= best_st->index_entries[i].timestamp
  601. * FFMAX(1, best_ast->sample_size);
  602. }
  603. // av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
  604. if(i>=0){
  605. int64_t pos= best_st->index_entries[i].pos;
  606. pos += best_ast->packet_size - best_ast->remaining;
  607. url_fseek(s->pb, pos + 8, SEEK_SET);
  608. // av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  609. assert(best_ast->remaining <= best_ast->packet_size);
  610. avi->stream_index= best_stream_index;
  611. if(!best_ast->remaining)
  612. best_ast->packet_size=
  613. best_ast->remaining= best_st->index_entries[i].size;
  614. }
  615. }
  616. resync:
  617. if(avi->stream_index >= 0){
  618. AVStream *st= s->streams[ avi->stream_index ];
  619. AVIStream *ast= st->priv_data;
  620. int size;
  621. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  622. size= INT_MAX;
  623. else if(ast->sample_size < 32)
  624. size= 64*ast->sample_size;
  625. else
  626. size= ast->sample_size;
  627. if(size > ast->remaining)
  628. size= ast->remaining;
  629. avi->last_pkt_pos= url_ftell(pb);
  630. av_get_packet(pb, pkt, size);
  631. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  632. ast->has_pal=0;
  633. pkt->size += 4*256;
  634. pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  635. if(pkt->data)
  636. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  637. }
  638. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  639. dstr = pkt->destruct;
  640. size = dv_produce_packet(avi->dv_demux, pkt,
  641. pkt->data, pkt->size);
  642. pkt->destruct = dstr;
  643. pkt->flags |= PKT_FLAG_KEY;
  644. } else {
  645. /* XXX: How to handle B-frames in AVI? */
  646. pkt->dts = ast->frame_offset;
  647. // pkt->dts += ast->start;
  648. if(ast->sample_size)
  649. pkt->dts /= ast->sample_size;
  650. //av_log(NULL, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
  651. pkt->stream_index = avi->stream_index;
  652. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  653. AVIndexEntry *e;
  654. int index;
  655. assert(st->index_entries);
  656. index= av_index_search_timestamp(st, pkt->dts, 0);
  657. e= &st->index_entries[index];
  658. if(index >= 0 && e->timestamp == ast->frame_offset){
  659. if (e->flags & AVINDEX_KEYFRAME)
  660. pkt->flags |= PKT_FLAG_KEY;
  661. }
  662. } else {
  663. pkt->flags |= PKT_FLAG_KEY;
  664. }
  665. if(ast->sample_size)
  666. ast->frame_offset += pkt->size;
  667. else
  668. ast->frame_offset++;
  669. }
  670. ast->remaining -= size;
  671. if(!ast->remaining){
  672. avi->stream_index= -1;
  673. ast->packet_size= 0;
  674. }
  675. return size;
  676. }
  677. memset(d, -1, sizeof(int)*8);
  678. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  679. int j;
  680. for(j=0; j<7; j++)
  681. d[j]= d[j+1];
  682. d[7]= get_byte(pb);
  683. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  684. n= get_stream_idx(d+2);
  685. //av_log(NULL, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  686. if(i + size > avi->fsize || d[0]<0)
  687. continue;
  688. //parse ix##
  689. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  690. //parse JUNK
  691. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  692. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  693. url_fskip(pb, size);
  694. //av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
  695. goto resync;
  696. }
  697. n= get_stream_idx(d);
  698. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  699. continue;
  700. //parse ##dc/##wb
  701. if(n < s->nb_streams){
  702. AVStream *st;
  703. AVIStream *ast;
  704. st = s->streams[n];
  705. ast = st->priv_data;
  706. if(s->nb_streams>=2){
  707. AVStream *st1 = s->streams[1];
  708. AVIStream *ast1= st1->priv_data;
  709. //workaround for broken small-file-bug402.avi
  710. if( d[2] == 'w' && d[3] == 'b'
  711. && n==0
  712. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  713. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  714. && ast->prefix == 'd'*256+'c'
  715. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  716. ){
  717. n=1;
  718. st = st1;
  719. ast = ast1;
  720. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  721. }
  722. }
  723. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  724. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  725. || st->discard >= AVDISCARD_ALL){
  726. if(ast->sample_size) ast->frame_offset += pkt->size;
  727. else ast->frame_offset++;
  728. url_fskip(pb, size);
  729. goto resync;
  730. }
  731. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  732. int k = get_byte(pb);
  733. int last = (k + get_byte(pb) - 1) & 0xFF;
  734. get_le16(pb); //flags
  735. for (; k <= last; k++)
  736. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  737. ast->has_pal= 1;
  738. goto resync;
  739. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  740. d[2]*256+d[3] == ast->prefix /*||
  741. (d[2] == 'd' && d[3] == 'c') ||
  742. (d[2] == 'w' && d[3] == 'b')*/) {
  743. //av_log(NULL, AV_LOG_DEBUG, "OK\n");
  744. if(d[2]*256+d[3] == ast->prefix)
  745. ast->prefix_count++;
  746. else{
  747. ast->prefix= d[2]*256+d[3];
  748. ast->prefix_count= 0;
  749. }
  750. avi->stream_index= n;
  751. ast->packet_size= size + 8;
  752. ast->remaining= size;
  753. {
  754. uint64_t pos= url_ftell(pb) - 8;
  755. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  756. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  757. }
  758. }
  759. goto resync;
  760. }
  761. }
  762. }
  763. return -1;
  764. }
  765. /* XXX: We make the implicit supposition that the positions are sorted
  766. for each stream. */
  767. static int avi_read_idx1(AVFormatContext *s, int size)
  768. {
  769. AVIContext *avi = s->priv_data;
  770. ByteIOContext *pb = s->pb;
  771. int nb_index_entries, i;
  772. AVStream *st;
  773. AVIStream *ast;
  774. unsigned int index, tag, flags, pos, len;
  775. unsigned last_pos= -1;
  776. nb_index_entries = size / 16;
  777. if (nb_index_entries <= 0)
  778. return -1;
  779. /* Read the entries and sort them in each stream component. */
  780. for(i = 0; i < nb_index_entries; i++) {
  781. tag = get_le32(pb);
  782. flags = get_le32(pb);
  783. pos = get_le32(pb);
  784. len = get_le32(pb);
  785. #if defined(DEBUG_SEEK)
  786. av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  787. i, tag, flags, pos, len);
  788. #endif
  789. if(i==0 && pos > avi->movi_list)
  790. avi->movi_list= 0; //FIXME better check
  791. pos += avi->movi_list;
  792. index = ((tag & 0xff) - '0') * 10;
  793. index += ((tag >> 8) & 0xff) - '0';
  794. if (index >= s->nb_streams)
  795. continue;
  796. st = s->streams[index];
  797. ast = st->priv_data;
  798. #if defined(DEBUG_SEEK)
  799. av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  800. #endif
  801. if(last_pos == pos)
  802. avi->non_interleaved= 1;
  803. else
  804. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  805. if(ast->sample_size)
  806. ast->cum_len += len;
  807. else
  808. ast->cum_len ++;
  809. last_pos= pos;
  810. }
  811. return 0;
  812. }
  813. static int guess_ni_flag(AVFormatContext *s){
  814. int i;
  815. int64_t last_start=0;
  816. int64_t first_end= INT64_MAX;
  817. for(i=0; i<s->nb_streams; i++){
  818. AVStream *st = s->streams[i];
  819. int n= st->nb_index_entries;
  820. if(n <= 0)
  821. continue;
  822. if(st->index_entries[0].pos > last_start)
  823. last_start= st->index_entries[0].pos;
  824. if(st->index_entries[n-1].pos < first_end)
  825. first_end= st->index_entries[n-1].pos;
  826. }
  827. return last_start > first_end;
  828. }
  829. static int avi_load_index(AVFormatContext *s)
  830. {
  831. AVIContext *avi = s->priv_data;
  832. ByteIOContext *pb = s->pb;
  833. uint32_t tag, size;
  834. int64_t pos= url_ftell(pb);
  835. url_fseek(pb, avi->movi_end, SEEK_SET);
  836. #ifdef DEBUG_SEEK
  837. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  838. #endif
  839. for(;;) {
  840. if (url_feof(pb))
  841. break;
  842. tag = get_le32(pb);
  843. size = get_le32(pb);
  844. #ifdef DEBUG_SEEK
  845. printf("tag=%c%c%c%c size=0x%x\n",
  846. tag & 0xff,
  847. (tag >> 8) & 0xff,
  848. (tag >> 16) & 0xff,
  849. (tag >> 24) & 0xff,
  850. size);
  851. #endif
  852. switch(tag) {
  853. case MKTAG('i', 'd', 'x', '1'):
  854. if (avi_read_idx1(s, size) < 0)
  855. goto skip;
  856. else
  857. goto the_end;
  858. break;
  859. default:
  860. skip:
  861. size += (size & 1);
  862. url_fskip(pb, size);
  863. break;
  864. }
  865. }
  866. the_end:
  867. url_fseek(pb, pos, SEEK_SET);
  868. return 0;
  869. }
  870. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  871. {
  872. AVIContext *avi = s->priv_data;
  873. AVStream *st;
  874. int i, index;
  875. int64_t pos;
  876. if (!avi->index_loaded) {
  877. /* we only load the index on demand */
  878. avi_load_index(s);
  879. avi->index_loaded = 1;
  880. }
  881. assert(stream_index>= 0);
  882. st = s->streams[stream_index];
  883. index= av_index_search_timestamp(st, timestamp, flags);
  884. if(index<0)
  885. return -1;
  886. /* find the position */
  887. pos = st->index_entries[index].pos;
  888. timestamp = st->index_entries[index].timestamp;
  889. // av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  890. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  891. /* One and only one real stream for DV in AVI, and it has video */
  892. /* offsets. Calling with other stream indexes should have failed */
  893. /* the av_index_search_timestamp call above. */
  894. assert(stream_index == 0);
  895. /* Feed the DV video stream version of the timestamp to the */
  896. /* DV demux so it can synthesize correct timestamps. */
  897. dv_offset_reset(avi->dv_demux, timestamp);
  898. url_fseek(s->pb, pos, SEEK_SET);
  899. avi->stream_index= -1;
  900. return 0;
  901. }
  902. for(i = 0; i < s->nb_streams; i++) {
  903. AVStream *st2 = s->streams[i];
  904. AVIStream *ast2 = st2->priv_data;
  905. ast2->packet_size=
  906. ast2->remaining= 0;
  907. if (st2->nb_index_entries <= 0)
  908. continue;
  909. // assert(st2->codec->block_align);
  910. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  911. index = av_index_search_timestamp(
  912. st2,
  913. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  914. flags | AVSEEK_FLAG_BACKWARD);
  915. if(index<0)
  916. index=0;
  917. if(!avi->non_interleaved){
  918. while(index>0 && st2->index_entries[index].pos > pos)
  919. index--;
  920. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  921. index++;
  922. }
  923. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  924. /* extract the current frame number */
  925. ast2->frame_offset = st2->index_entries[index].timestamp;
  926. if(ast2->sample_size)
  927. ast2->frame_offset *=ast2->sample_size;
  928. }
  929. /* do the seek */
  930. url_fseek(s->pb, pos, SEEK_SET);
  931. avi->stream_index= -1;
  932. return 0;
  933. }
  934. static int avi_read_close(AVFormatContext *s)
  935. {
  936. int i;
  937. AVIContext *avi = s->priv_data;
  938. for(i=0;i<s->nb_streams;i++) {
  939. AVStream *st = s->streams[i];
  940. av_free(st->codec->palctrl);
  941. }
  942. if (avi->dv_demux)
  943. av_free(avi->dv_demux);
  944. return 0;
  945. }
  946. static int avi_probe(AVProbeData *p)
  947. {
  948. int i;
  949. /* check file header */
  950. for(i=0; avi_headers[i][0]; i++)
  951. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  952. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  953. return AVPROBE_SCORE_MAX;
  954. return 0;
  955. }
  956. AVInputFormat avi_demuxer = {
  957. "avi",
  958. NULL_IF_CONFIG_SMALL("AVI format"),
  959. sizeof(AVIContext),
  960. avi_probe,
  961. avi_read_header,
  962. avi_read_packet,
  963. avi_read_close,
  964. avi_read_seek,
  965. };