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.

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