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.

1119 lines
37KB

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