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.

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