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.

1120 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];
  573. unsigned int size;
  574. int64_t i, sync;
  575. void* dstr;
  576. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  577. int size = dv_get_packet(avi->dv_demux, pkt);
  578. if (size >= 0)
  579. return size;
  580. }
  581. if(avi->non_interleaved){
  582. int best_stream_index = 0;
  583. AVStream *best_st= NULL;
  584. AVIStream *best_ast;
  585. int64_t best_ts= INT64_MAX;
  586. int i;
  587. for(i=0; i<s->nb_streams; i++){
  588. AVStream *st = s->streams[i];
  589. AVIStream *ast = st->priv_data;
  590. int64_t ts= ast->frame_offset;
  591. if(ast->sample_size)
  592. ts /= ast->sample_size;
  593. ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  594. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  595. if(ts < best_ts && st->nb_index_entries){
  596. best_ts= ts;
  597. best_st= st;
  598. best_stream_index= i;
  599. }
  600. }
  601. if(!best_st)
  602. return -1;
  603. best_ast = best_st->priv_data;
  604. 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
  605. if(best_ast->remaining)
  606. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  607. else{
  608. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  609. if(i>=0)
  610. best_ast->frame_offset= best_st->index_entries[i].timestamp
  611. * FFMAX(1, best_ast->sample_size);
  612. }
  613. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  614. if(i>=0){
  615. int64_t pos= best_st->index_entries[i].pos;
  616. pos += best_ast->packet_size - best_ast->remaining;
  617. url_fseek(s->pb, pos + 8, SEEK_SET);
  618. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  619. assert(best_ast->remaining <= best_ast->packet_size);
  620. avi->stream_index= best_stream_index;
  621. if(!best_ast->remaining)
  622. best_ast->packet_size=
  623. best_ast->remaining= best_st->index_entries[i].size;
  624. }
  625. }
  626. resync:
  627. if(avi->stream_index >= 0){
  628. AVStream *st= s->streams[ avi->stream_index ];
  629. AVIStream *ast= st->priv_data;
  630. int size;
  631. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  632. size= INT_MAX;
  633. else if(ast->sample_size < 32)
  634. size= 64*ast->sample_size;
  635. else
  636. size= ast->sample_size;
  637. if(size > ast->remaining)
  638. size= ast->remaining;
  639. avi->last_pkt_pos= url_ftell(pb);
  640. av_get_packet(pb, pkt, size);
  641. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  642. ast->has_pal=0;
  643. pkt->size += 4*256;
  644. pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  645. if(pkt->data)
  646. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  647. }
  648. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  649. dstr = pkt->destruct;
  650. size = dv_produce_packet(avi->dv_demux, pkt,
  651. pkt->data, pkt->size);
  652. pkt->destruct = dstr;
  653. pkt->flags |= PKT_FLAG_KEY;
  654. } else {
  655. /* XXX: How to handle B-frames in AVI? */
  656. pkt->dts = ast->frame_offset;
  657. // pkt->dts += ast->start;
  658. if(ast->sample_size)
  659. pkt->dts /= ast->sample_size;
  660. //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);
  661. pkt->stream_index = avi->stream_index;
  662. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  663. AVIndexEntry *e;
  664. int index;
  665. assert(st->index_entries);
  666. index= av_index_search_timestamp(st, pkt->dts, 0);
  667. e= &st->index_entries[index];
  668. if(index >= 0 && e->timestamp == ast->frame_offset){
  669. if (e->flags & AVINDEX_KEYFRAME)
  670. pkt->flags |= PKT_FLAG_KEY;
  671. }
  672. } else {
  673. pkt->flags |= PKT_FLAG_KEY;
  674. }
  675. if(ast->sample_size)
  676. ast->frame_offset += pkt->size;
  677. else
  678. ast->frame_offset++;
  679. }
  680. ast->remaining -= size;
  681. if(!ast->remaining){
  682. avi->stream_index= -1;
  683. ast->packet_size= 0;
  684. }
  685. return size;
  686. }
  687. memset(d, -1, sizeof(int)*8);
  688. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  689. int j;
  690. for(j=0; j<7; j++)
  691. d[j]= d[j+1];
  692. d[7]= get_byte(pb);
  693. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  694. n= get_stream_idx(d+2);
  695. //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);
  696. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  697. continue;
  698. //parse ix##
  699. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  700. //parse JUNK
  701. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  702. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  703. url_fskip(pb, size);
  704. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  705. goto resync;
  706. }
  707. n= get_stream_idx(d);
  708. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  709. continue;
  710. //parse ##dc/##wb
  711. if(n < s->nb_streams){
  712. AVStream *st;
  713. AVIStream *ast;
  714. st = s->streams[n];
  715. ast = st->priv_data;
  716. if(s->nb_streams>=2){
  717. AVStream *st1 = s->streams[1];
  718. AVIStream *ast1= st1->priv_data;
  719. //workaround for broken small-file-bug402.avi
  720. if( d[2] == 'w' && d[3] == 'b'
  721. && n==0
  722. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  723. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  724. && ast->prefix == 'd'*256+'c'
  725. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  726. ){
  727. n=1;
  728. st = st1;
  729. ast = ast1;
  730. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  731. }
  732. }
  733. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  734. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  735. || st->discard >= AVDISCARD_ALL){
  736. if(ast->sample_size) ast->frame_offset += pkt->size;
  737. else ast->frame_offset++;
  738. url_fskip(pb, size);
  739. goto resync;
  740. }
  741. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  742. int k = get_byte(pb);
  743. int last = (k + get_byte(pb) - 1) & 0xFF;
  744. get_le16(pb); //flags
  745. for (; k <= last; k++)
  746. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  747. ast->has_pal= 1;
  748. goto resync;
  749. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  750. d[2]*256+d[3] == ast->prefix /*||
  751. (d[2] == 'd' && d[3] == 'c') ||
  752. (d[2] == 'w' && d[3] == 'b')*/) {
  753. //av_log(s, AV_LOG_DEBUG, "OK\n");
  754. if(d[2]*256+d[3] == ast->prefix)
  755. ast->prefix_count++;
  756. else{
  757. ast->prefix= d[2]*256+d[3];
  758. ast->prefix_count= 0;
  759. }
  760. avi->stream_index= n;
  761. ast->packet_size= size + 8;
  762. ast->remaining= size;
  763. {
  764. uint64_t pos= url_ftell(pb) - 8;
  765. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  766. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  767. }
  768. }
  769. goto resync;
  770. }
  771. }
  772. }
  773. return AVERROR_EOF;
  774. }
  775. /* XXX: We make the implicit supposition that the positions are sorted
  776. for each stream. */
  777. static int avi_read_idx1(AVFormatContext *s, int size)
  778. {
  779. AVIContext *avi = s->priv_data;
  780. ByteIOContext *pb = s->pb;
  781. int nb_index_entries, i;
  782. AVStream *st;
  783. AVIStream *ast;
  784. unsigned int index, tag, flags, pos, len;
  785. unsigned last_pos= -1;
  786. nb_index_entries = size / 16;
  787. if (nb_index_entries <= 0)
  788. return -1;
  789. /* Read the entries and sort them in each stream component. */
  790. for(i = 0; i < nb_index_entries; i++) {
  791. tag = get_le32(pb);
  792. flags = get_le32(pb);
  793. pos = get_le32(pb);
  794. len = get_le32(pb);
  795. #if defined(DEBUG_SEEK)
  796. av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  797. i, tag, flags, pos, len);
  798. #endif
  799. if(i==0 && pos > avi->movi_list)
  800. avi->movi_list= 0; //FIXME better check
  801. pos += avi->movi_list;
  802. index = ((tag & 0xff) - '0') * 10;
  803. index += ((tag >> 8) & 0xff) - '0';
  804. if (index >= s->nb_streams)
  805. continue;
  806. st = s->streams[index];
  807. ast = st->priv_data;
  808. #if defined(DEBUG_SEEK)
  809. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  810. #endif
  811. if(last_pos == pos)
  812. avi->non_interleaved= 1;
  813. else
  814. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  815. if(ast->sample_size)
  816. ast->cum_len += len;
  817. else
  818. ast->cum_len ++;
  819. last_pos= pos;
  820. }
  821. return 0;
  822. }
  823. static int guess_ni_flag(AVFormatContext *s){
  824. int i;
  825. int64_t last_start=0;
  826. int64_t first_end= INT64_MAX;
  827. for(i=0; i<s->nb_streams; i++){
  828. AVStream *st = s->streams[i];
  829. int n= st->nb_index_entries;
  830. if(n <= 0)
  831. continue;
  832. if(st->index_entries[0].pos > last_start)
  833. last_start= st->index_entries[0].pos;
  834. if(st->index_entries[n-1].pos < first_end)
  835. first_end= st->index_entries[n-1].pos;
  836. }
  837. return last_start > first_end;
  838. }
  839. static int avi_load_index(AVFormatContext *s)
  840. {
  841. AVIContext *avi = s->priv_data;
  842. ByteIOContext *pb = s->pb;
  843. uint32_t tag, size;
  844. int64_t pos= url_ftell(pb);
  845. url_fseek(pb, avi->movi_end, SEEK_SET);
  846. #ifdef DEBUG_SEEK
  847. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  848. #endif
  849. for(;;) {
  850. if (url_feof(pb))
  851. break;
  852. tag = get_le32(pb);
  853. size = get_le32(pb);
  854. #ifdef DEBUG_SEEK
  855. printf("tag=%c%c%c%c size=0x%x\n",
  856. tag & 0xff,
  857. (tag >> 8) & 0xff,
  858. (tag >> 16) & 0xff,
  859. (tag >> 24) & 0xff,
  860. size);
  861. #endif
  862. switch(tag) {
  863. case MKTAG('i', 'd', 'x', '1'):
  864. if (avi_read_idx1(s, size) < 0)
  865. goto skip;
  866. else
  867. goto the_end;
  868. break;
  869. default:
  870. skip:
  871. size += (size & 1);
  872. url_fskip(pb, size);
  873. break;
  874. }
  875. }
  876. the_end:
  877. url_fseek(pb, pos, SEEK_SET);
  878. return 0;
  879. }
  880. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  881. {
  882. AVIContext *avi = s->priv_data;
  883. AVStream *st;
  884. int i, index;
  885. int64_t pos;
  886. if (!avi->index_loaded) {
  887. /* we only load the index on demand */
  888. avi_load_index(s);
  889. avi->index_loaded = 1;
  890. }
  891. assert(stream_index>= 0);
  892. st = s->streams[stream_index];
  893. index= av_index_search_timestamp(st, timestamp, flags);
  894. if(index<0)
  895. return -1;
  896. /* find the position */
  897. pos = st->index_entries[index].pos;
  898. timestamp = st->index_entries[index].timestamp;
  899. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  900. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  901. /* One and only one real stream for DV in AVI, and it has video */
  902. /* offsets. Calling with other stream indexes should have failed */
  903. /* the av_index_search_timestamp call above. */
  904. assert(stream_index == 0);
  905. /* Feed the DV video stream version of the timestamp to the */
  906. /* DV demux so it can synthesize correct timestamps. */
  907. dv_offset_reset(avi->dv_demux, timestamp);
  908. url_fseek(s->pb, pos, SEEK_SET);
  909. avi->stream_index= -1;
  910. return 0;
  911. }
  912. for(i = 0; i < s->nb_streams; i++) {
  913. AVStream *st2 = s->streams[i];
  914. AVIStream *ast2 = st2->priv_data;
  915. ast2->packet_size=
  916. ast2->remaining= 0;
  917. if (st2->nb_index_entries <= 0)
  918. continue;
  919. // assert(st2->codec->block_align);
  920. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  921. index = av_index_search_timestamp(
  922. st2,
  923. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  924. flags | AVSEEK_FLAG_BACKWARD);
  925. if(index<0)
  926. index=0;
  927. if(!avi->non_interleaved){
  928. while(index>0 && st2->index_entries[index].pos > pos)
  929. index--;
  930. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  931. index++;
  932. }
  933. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  934. /* extract the current frame number */
  935. ast2->frame_offset = st2->index_entries[index].timestamp;
  936. if(ast2->sample_size)
  937. ast2->frame_offset *=ast2->sample_size;
  938. }
  939. /* do the seek */
  940. url_fseek(s->pb, pos, SEEK_SET);
  941. avi->stream_index= -1;
  942. return 0;
  943. }
  944. static int avi_read_close(AVFormatContext *s)
  945. {
  946. int i;
  947. AVIContext *avi = s->priv_data;
  948. for(i=0;i<s->nb_streams;i++) {
  949. AVStream *st = s->streams[i];
  950. av_free(st->codec->palctrl);
  951. }
  952. if (avi->dv_demux)
  953. av_free(avi->dv_demux);
  954. return 0;
  955. }
  956. static int avi_probe(AVProbeData *p)
  957. {
  958. int i;
  959. /* check file header */
  960. for(i=0; avi_headers[i][0]; i++)
  961. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  962. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  963. return AVPROBE_SCORE_MAX;
  964. return 0;
  965. }
  966. AVInputFormat avi_demuxer = {
  967. "avi",
  968. NULL_IF_CONFIG_SMALL("AVI format"),
  969. sizeof(AVIContext),
  970. avi_probe,
  971. avi_read_header,
  972. avi_read_packet,
  973. avi_read_close,
  974. avi_read_seek,
  975. };