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.

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