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.

1171 lines
39KB

  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. int64_t last_ts;
  603. if(!st->nb_index_entries)
  604. continue;
  605. if(ast->sample_size)
  606. ts /= ast->sample_size;
  607. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  608. if(!ast->remaining && ts > last_ts)
  609. continue;
  610. ts = av_rescale_q(ts, st->time_base, AV_TIME_BASE_Q);
  611. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  612. if(ts < best_ts){
  613. best_ts= ts;
  614. best_st= st;
  615. best_stream_index= i;
  616. }
  617. }
  618. if(!best_st)
  619. return -1;
  620. best_ast = best_st->priv_data;
  621. best_ts = av_rescale_q(best_ts, AV_TIME_BASE_Q, best_st->time_base);
  622. if(best_ast->remaining)
  623. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  624. else{
  625. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  626. if(i>=0)
  627. best_ast->frame_offset= best_st->index_entries[i].timestamp
  628. * FFMAX(1, best_ast->sample_size);
  629. }
  630. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  631. if(i>=0){
  632. int64_t pos= best_st->index_entries[i].pos;
  633. pos += best_ast->packet_size - best_ast->remaining;
  634. url_fseek(s->pb, pos + 8, SEEK_SET);
  635. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  636. assert(best_ast->remaining <= best_ast->packet_size);
  637. avi->stream_index= best_stream_index;
  638. if(!best_ast->remaining)
  639. best_ast->packet_size=
  640. best_ast->remaining= best_st->index_entries[i].size;
  641. }
  642. }
  643. resync:
  644. if(avi->stream_index >= 0){
  645. AVStream *st= s->streams[ avi->stream_index ];
  646. AVIStream *ast= st->priv_data;
  647. int size, err;
  648. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  649. size= INT_MAX;
  650. else if(ast->sample_size < 32)
  651. size= 64*ast->sample_size;
  652. else
  653. size= ast->sample_size;
  654. if(size > ast->remaining)
  655. size= ast->remaining;
  656. avi->last_pkt_pos= url_ftell(pb);
  657. err= av_get_packet(pb, pkt, size);
  658. if(err<0)
  659. return err;
  660. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  661. void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
  662. if(ptr){
  663. ast->has_pal=0;
  664. pkt->size += 4*256;
  665. pkt->data= ptr;
  666. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  667. }else
  668. av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
  669. }
  670. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  671. dstr = pkt->destruct;
  672. size = dv_produce_packet(avi->dv_demux, pkt,
  673. pkt->data, pkt->size);
  674. pkt->destruct = dstr;
  675. pkt->flags |= PKT_FLAG_KEY;
  676. } else {
  677. /* XXX: How to handle B-frames in AVI? */
  678. pkt->dts = ast->frame_offset;
  679. // pkt->dts += ast->start;
  680. if(ast->sample_size)
  681. pkt->dts /= ast->sample_size;
  682. //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);
  683. pkt->stream_index = avi->stream_index;
  684. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  685. AVIndexEntry *e;
  686. int index;
  687. assert(st->index_entries);
  688. index= av_index_search_timestamp(st, pkt->dts, 0);
  689. e= &st->index_entries[index];
  690. if(index >= 0 && e->timestamp == ast->frame_offset){
  691. if (e->flags & AVINDEX_KEYFRAME)
  692. pkt->flags |= PKT_FLAG_KEY;
  693. }
  694. } else {
  695. pkt->flags |= PKT_FLAG_KEY;
  696. }
  697. if(ast->sample_size)
  698. ast->frame_offset += pkt->size;
  699. else
  700. ast->frame_offset++;
  701. }
  702. ast->remaining -= size;
  703. if(!ast->remaining){
  704. avi->stream_index= -1;
  705. ast->packet_size= 0;
  706. }
  707. return size;
  708. }
  709. memset(d, -1, sizeof(int)*8);
  710. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  711. int j;
  712. for(j=0; j<7; j++)
  713. d[j]= d[j+1];
  714. d[7]= get_byte(pb);
  715. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  716. n= get_stream_idx(d+2);
  717. //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);
  718. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  719. continue;
  720. //parse ix##
  721. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  722. //parse JUNK
  723. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  724. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  725. url_fskip(pb, size);
  726. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  727. goto resync;
  728. }
  729. n= get_stream_idx(d);
  730. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  731. continue;
  732. //detect ##ix chunk and skip
  733. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  734. url_fskip(pb, size);
  735. goto resync;
  736. }
  737. //parse ##dc/##wb
  738. if(n < s->nb_streams){
  739. AVStream *st;
  740. AVIStream *ast;
  741. st = s->streams[n];
  742. ast = st->priv_data;
  743. if(s->nb_streams>=2){
  744. AVStream *st1 = s->streams[1];
  745. AVIStream *ast1= st1->priv_data;
  746. //workaround for broken small-file-bug402.avi
  747. if( d[2] == 'w' && d[3] == 'b'
  748. && n==0
  749. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  750. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  751. && ast->prefix == 'd'*256+'c'
  752. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  753. ){
  754. n=1;
  755. st = st1;
  756. ast = ast1;
  757. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  758. }
  759. }
  760. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  761. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  762. || st->discard >= AVDISCARD_ALL){
  763. if(ast->sample_size) ast->frame_offset += pkt->size;
  764. else ast->frame_offset++;
  765. url_fskip(pb, size);
  766. goto resync;
  767. }
  768. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  769. int k = get_byte(pb);
  770. int last = (k + get_byte(pb) - 1) & 0xFF;
  771. get_le16(pb); //flags
  772. for (; k <= last; k++)
  773. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  774. ast->has_pal= 1;
  775. goto resync;
  776. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  777. d[2]*256+d[3] == ast->prefix /*||
  778. (d[2] == 'd' && d[3] == 'c') ||
  779. (d[2] == 'w' && d[3] == 'b')*/) {
  780. //av_log(s, AV_LOG_DEBUG, "OK\n");
  781. if(d[2]*256+d[3] == ast->prefix)
  782. ast->prefix_count++;
  783. else{
  784. ast->prefix= d[2]*256+d[3];
  785. ast->prefix_count= 0;
  786. }
  787. avi->stream_index= n;
  788. ast->packet_size= size + 8;
  789. ast->remaining= size;
  790. {
  791. uint64_t pos= url_ftell(pb) - 8;
  792. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  793. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  794. }
  795. }
  796. goto resync;
  797. }
  798. }
  799. }
  800. return AVERROR_EOF;
  801. }
  802. /* XXX: We make the implicit supposition that the positions are sorted
  803. for each stream. */
  804. static int avi_read_idx1(AVFormatContext *s, int size)
  805. {
  806. AVIContext *avi = s->priv_data;
  807. ByteIOContext *pb = s->pb;
  808. int nb_index_entries, i;
  809. AVStream *st;
  810. AVIStream *ast;
  811. unsigned int index, tag, flags, pos, len;
  812. unsigned last_pos= -1;
  813. nb_index_entries = size / 16;
  814. if (nb_index_entries <= 0)
  815. return -1;
  816. /* Read the entries and sort them in each stream component. */
  817. for(i = 0; i < nb_index_entries; i++) {
  818. tag = get_le32(pb);
  819. flags = get_le32(pb);
  820. pos = get_le32(pb);
  821. len = get_le32(pb);
  822. #if defined(DEBUG_SEEK)
  823. av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  824. i, tag, flags, pos, len);
  825. #endif
  826. if(i==0 && pos > avi->movi_list)
  827. avi->movi_list= 0; //FIXME better check
  828. pos += avi->movi_list;
  829. index = ((tag & 0xff) - '0') * 10;
  830. index += ((tag >> 8) & 0xff) - '0';
  831. if (index >= s->nb_streams)
  832. continue;
  833. st = s->streams[index];
  834. ast = st->priv_data;
  835. #if defined(DEBUG_SEEK)
  836. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  837. #endif
  838. if(url_feof(pb))
  839. return -1;
  840. if(last_pos == pos)
  841. avi->non_interleaved= 1;
  842. else
  843. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  844. if(ast->sample_size)
  845. ast->cum_len += len;
  846. else
  847. ast->cum_len ++;
  848. last_pos= pos;
  849. }
  850. return 0;
  851. }
  852. static int guess_ni_flag(AVFormatContext *s){
  853. int i;
  854. int64_t last_start=0;
  855. int64_t first_end= INT64_MAX;
  856. int64_t oldpos= url_ftell(s->pb);
  857. for(i=0; i<s->nb_streams; i++){
  858. AVStream *st = s->streams[i];
  859. int n= st->nb_index_entries;
  860. unsigned int size;
  861. if(n <= 0)
  862. continue;
  863. if(n >= 2){
  864. int64_t pos= st->index_entries[0].pos;
  865. url_fseek(s->pb, pos + 4, SEEK_SET);
  866. size= get_le32(s->pb);
  867. if(pos + size > st->index_entries[1].pos)
  868. last_start= INT64_MAX;
  869. }
  870. if(st->index_entries[0].pos > last_start)
  871. last_start= st->index_entries[0].pos;
  872. if(st->index_entries[n-1].pos < first_end)
  873. first_end= st->index_entries[n-1].pos;
  874. }
  875. url_fseek(s->pb, oldpos, SEEK_SET);
  876. return last_start > first_end;
  877. }
  878. static int avi_load_index(AVFormatContext *s)
  879. {
  880. AVIContext *avi = s->priv_data;
  881. ByteIOContext *pb = s->pb;
  882. uint32_t tag, size;
  883. int64_t pos= url_ftell(pb);
  884. int ret = -1;
  885. if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
  886. goto the_end; // maybe truncated file
  887. #ifdef DEBUG_SEEK
  888. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  889. #endif
  890. for(;;) {
  891. if (url_feof(pb))
  892. break;
  893. tag = get_le32(pb);
  894. size = get_le32(pb);
  895. #ifdef DEBUG_SEEK
  896. printf("tag=%c%c%c%c size=0x%x\n",
  897. tag & 0xff,
  898. (tag >> 8) & 0xff,
  899. (tag >> 16) & 0xff,
  900. (tag >> 24) & 0xff,
  901. size);
  902. #endif
  903. switch(tag) {
  904. case MKTAG('i', 'd', 'x', '1'):
  905. if (avi_read_idx1(s, size) < 0)
  906. goto skip;
  907. ret = 0;
  908. goto the_end;
  909. break;
  910. default:
  911. skip:
  912. size += (size & 1);
  913. if (url_fseek(pb, size, SEEK_CUR) < 0)
  914. goto the_end; // something is wrong here
  915. break;
  916. }
  917. }
  918. the_end:
  919. url_fseek(pb, pos, SEEK_SET);
  920. return ret;
  921. }
  922. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  923. {
  924. AVIContext *avi = s->priv_data;
  925. AVStream *st;
  926. int i, index;
  927. int64_t pos;
  928. if (!avi->index_loaded) {
  929. /* we only load the index on demand */
  930. avi_load_index(s);
  931. avi->index_loaded = 1;
  932. }
  933. assert(stream_index>= 0);
  934. st = s->streams[stream_index];
  935. index= av_index_search_timestamp(st, timestamp, flags);
  936. if(index<0)
  937. return -1;
  938. /* find the position */
  939. pos = st->index_entries[index].pos;
  940. timestamp = st->index_entries[index].timestamp;
  941. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  942. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  943. /* One and only one real stream for DV in AVI, and it has video */
  944. /* offsets. Calling with other stream indexes should have failed */
  945. /* the av_index_search_timestamp call above. */
  946. assert(stream_index == 0);
  947. /* Feed the DV video stream version of the timestamp to the */
  948. /* DV demux so it can synthesize correct timestamps. */
  949. dv_offset_reset(avi->dv_demux, timestamp);
  950. url_fseek(s->pb, pos, SEEK_SET);
  951. avi->stream_index= -1;
  952. return 0;
  953. }
  954. for(i = 0; i < s->nb_streams; i++) {
  955. AVStream *st2 = s->streams[i];
  956. AVIStream *ast2 = st2->priv_data;
  957. ast2->packet_size=
  958. ast2->remaining= 0;
  959. if (st2->nb_index_entries <= 0)
  960. continue;
  961. // assert(st2->codec->block_align);
  962. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  963. index = av_index_search_timestamp(
  964. st2,
  965. av_rescale_q(timestamp, st->time_base, st2->time_base),
  966. flags | AVSEEK_FLAG_BACKWARD);
  967. if(index<0)
  968. index=0;
  969. if(!avi->non_interleaved){
  970. while(index>0 && st2->index_entries[index].pos > pos)
  971. index--;
  972. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  973. index++;
  974. }
  975. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  976. /* extract the current frame number */
  977. ast2->frame_offset = st2->index_entries[index].timestamp;
  978. if(ast2->sample_size)
  979. ast2->frame_offset *=ast2->sample_size;
  980. }
  981. /* do the seek */
  982. url_fseek(s->pb, pos, SEEK_SET);
  983. avi->stream_index= -1;
  984. return 0;
  985. }
  986. static int avi_read_close(AVFormatContext *s)
  987. {
  988. int i;
  989. AVIContext *avi = s->priv_data;
  990. for(i=0;i<s->nb_streams;i++) {
  991. AVStream *st = s->streams[i];
  992. av_free(st->codec->palctrl);
  993. }
  994. if (avi->dv_demux)
  995. av_free(avi->dv_demux);
  996. return 0;
  997. }
  998. static int avi_probe(AVProbeData *p)
  999. {
  1000. int i;
  1001. /* check file header */
  1002. for(i=0; avi_headers[i][0]; i++)
  1003. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1004. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1005. return AVPROBE_SCORE_MAX;
  1006. return 0;
  1007. }
  1008. AVInputFormat avi_demuxer = {
  1009. "avi",
  1010. NULL_IF_CONFIG_SMALL("AVI format"),
  1011. sizeof(AVIContext),
  1012. avi_probe,
  1013. avi_read_header,
  1014. avi_read_packet,
  1015. avi_read_close,
  1016. avi_read_seek,
  1017. };