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.

1155 lines
38KB

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