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.

1034 lines
33KB

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