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.

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