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.

1054 lines
34KB

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