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.

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