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.

1173 lines
39KB

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