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.

1159 lines
38KB

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