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.

1214 lines
40KB

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