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.

1081 lines
35KB

  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_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  431. ast->sample_size= st->codec->block_align;
  432. }
  433. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  434. url_fskip(pb, 1);
  435. /* Force parsing as several audio frames can be in
  436. * one packet and timestamps refer to packet start*/
  437. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  438. /* ADTS header is in extradata, AAC without header must be stored as exact frames, parser not needed and it will fail */
  439. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  440. st->need_parsing = AVSTREAM_PARSE_NONE;
  441. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  442. * audio in the header but have Axan as stream_code_tag. */
  443. if (st->codec->stream_codec_tag == ff_get_fourcc("Axan")){
  444. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  445. st->codec->codec_tag = 0;
  446. }
  447. if (amv_file_format)
  448. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  449. break;
  450. default:
  451. st->codec->codec_type = CODEC_TYPE_DATA;
  452. st->codec->codec_id= CODEC_ID_NONE;
  453. st->codec->codec_tag= 0;
  454. url_fskip(pb, size);
  455. break;
  456. }
  457. }
  458. break;
  459. case MKTAG('i', 'n', 'd', 'x'):
  460. i= url_ftell(pb);
  461. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  462. read_braindead_odml_indx(s, 0);
  463. }
  464. url_fseek(pb, i+size, SEEK_SET);
  465. break;
  466. case MKTAG('v', 'p', 'r', 'p'):
  467. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  468. AVRational active, active_aspect;
  469. st = s->streams[stream_index];
  470. get_le32(pb);
  471. get_le32(pb);
  472. get_le32(pb);
  473. get_le32(pb);
  474. get_le32(pb);
  475. active_aspect.num= get_le16(pb);
  476. active_aspect.den= get_le16(pb);
  477. active.num = get_le32(pb);
  478. active.den = get_le32(pb);
  479. get_le32(pb); //nbFieldsPerFrame
  480. if(active_aspect.num && active_aspect.den && active.num && active.den){
  481. st->codec->sample_aspect_ratio= av_div_q(active_aspect, active);
  482. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  483. }
  484. size -= 9*4;
  485. }
  486. url_fseek(pb, size, SEEK_CUR);
  487. break;
  488. case MKTAG('I', 'N', 'A', 'M'):
  489. avi_read_tag(pb, s->title, sizeof(s->title), size);
  490. break;
  491. case MKTAG('I', 'A', 'R', 'T'):
  492. avi_read_tag(pb, s->author, sizeof(s->author), size);
  493. break;
  494. case MKTAG('I', 'C', 'O', 'P'):
  495. avi_read_tag(pb, s->copyright, sizeof(s->copyright), size);
  496. break;
  497. case MKTAG('I', 'C', 'M', 'T'):
  498. avi_read_tag(pb, s->comment, sizeof(s->comment), size);
  499. break;
  500. case MKTAG('I', 'G', 'N', 'R'):
  501. avi_read_tag(pb, s->genre, sizeof(s->genre), size);
  502. break;
  503. case MKTAG('I', 'P', 'R', 'D'):
  504. avi_read_tag(pb, s->album, sizeof(s->album), size);
  505. break;
  506. case MKTAG('I', 'P', 'R', 'T'):
  507. avi_read_tag(pb, str_track, sizeof(str_track), size);
  508. sscanf(str_track, "%d", &s->track);
  509. break;
  510. default:
  511. if(size > 1000000){
  512. av_log(s, AV_LOG_ERROR, "well something went wrong during header parsing, "
  513. "ill ignore it and try to continue anyway\n");
  514. avi->movi_list = url_ftell(pb) - 4;
  515. avi->movi_end = url_fsize(pb);
  516. goto end_of_header;
  517. }
  518. /* skip tag */
  519. size += (size & 1);
  520. url_fskip(pb, size);
  521. break;
  522. }
  523. }
  524. end_of_header:
  525. /* check stream number */
  526. if (stream_index != s->nb_streams - 1) {
  527. fail:
  528. for(i=0;i<s->nb_streams;i++) {
  529. av_freep(&s->streams[i]->codec->extradata);
  530. av_freep(&s->streams[i]);
  531. }
  532. return -1;
  533. }
  534. if(!avi->index_loaded && !url_is_streamed(pb))
  535. avi_load_index(s);
  536. avi->index_loaded = 1;
  537. avi->non_interleaved |= guess_ni_flag(s);
  538. if(avi->non_interleaved)
  539. clean_index(s);
  540. return 0;
  541. }
  542. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  543. {
  544. AVIContext *avi = s->priv_data;
  545. ByteIOContext *pb = s->pb;
  546. int n, d[8], size;
  547. offset_t i, sync;
  548. void* dstr;
  549. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  550. size = dv_get_packet(avi->dv_demux, pkt);
  551. if (size >= 0)
  552. return size;
  553. }
  554. if(avi->non_interleaved){
  555. int best_stream_index = 0;
  556. AVStream *best_st= NULL;
  557. AVIStream *best_ast;
  558. int64_t best_ts= INT64_MAX;
  559. int i;
  560. for(i=0; i<s->nb_streams; i++){
  561. AVStream *st = s->streams[i];
  562. AVIStream *ast = st->priv_data;
  563. int64_t ts= ast->frame_offset;
  564. if(ast->sample_size)
  565. ts /= ast->sample_size;
  566. ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  567. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  568. if(ts < best_ts){
  569. best_ts= ts;
  570. best_st= st;
  571. best_stream_index= i;
  572. }
  573. }
  574. best_ast = best_st->priv_data;
  575. 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
  576. if(best_ast->remaining)
  577. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  578. else
  579. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  580. // av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
  581. if(i>=0){
  582. int64_t pos= best_st->index_entries[i].pos;
  583. pos += best_ast->packet_size - best_ast->remaining;
  584. url_fseek(s->pb, pos + 8, SEEK_SET);
  585. // av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  586. assert(best_ast->remaining <= best_ast->packet_size);
  587. avi->stream_index= best_stream_index;
  588. if(!best_ast->remaining)
  589. best_ast->packet_size=
  590. best_ast->remaining= best_st->index_entries[i].size;
  591. }
  592. }
  593. resync:
  594. if(avi->stream_index >= 0){
  595. AVStream *st= s->streams[ avi->stream_index ];
  596. AVIStream *ast= st->priv_data;
  597. int size;
  598. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  599. size= INT_MAX;
  600. else if(ast->sample_size < 32)
  601. size= 64*ast->sample_size;
  602. else
  603. size= ast->sample_size;
  604. if(size > ast->remaining)
  605. size= ast->remaining;
  606. av_get_packet(pb, pkt, size);
  607. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  608. dstr = pkt->destruct;
  609. size = dv_produce_packet(avi->dv_demux, pkt,
  610. pkt->data, pkt->size);
  611. pkt->destruct = dstr;
  612. pkt->flags |= PKT_FLAG_KEY;
  613. } else {
  614. /* XXX: how to handle B frames in avi ? */
  615. pkt->dts = ast->frame_offset;
  616. // pkt->dts += ast->start;
  617. if(ast->sample_size)
  618. pkt->dts /= ast->sample_size;
  619. //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);
  620. pkt->stream_index = avi->stream_index;
  621. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  622. AVIndexEntry *e;
  623. int index;
  624. assert(st->index_entries);
  625. index= av_index_search_timestamp(st, pkt->dts, 0);
  626. e= &st->index_entries[index];
  627. if(index >= 0 && e->timestamp == ast->frame_offset){
  628. if (e->flags & AVINDEX_KEYFRAME)
  629. pkt->flags |= PKT_FLAG_KEY;
  630. }
  631. } else {
  632. pkt->flags |= PKT_FLAG_KEY;
  633. }
  634. if(ast->sample_size)
  635. ast->frame_offset += pkt->size;
  636. else
  637. ast->frame_offset++;
  638. }
  639. ast->remaining -= size;
  640. if(!ast->remaining){
  641. avi->stream_index= -1;
  642. ast->packet_size= 0;
  643. }
  644. return size;
  645. }
  646. memset(d, -1, sizeof(int)*8);
  647. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  648. int j;
  649. for(j=0; j<7; j++)
  650. d[j]= d[j+1];
  651. d[7]= get_byte(pb);
  652. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  653. if( d[2] >= '0' && d[2] <= '9'
  654. && d[3] >= '0' && d[3] <= '9'){
  655. n= (d[2] - '0') * 10 + (d[3] - '0');
  656. }else{
  657. n= 100; //invalid stream id
  658. }
  659. //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);
  660. if(i + size > avi->fsize || d[0]<0)
  661. continue;
  662. //parse ix##
  663. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  664. //parse JUNK
  665. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  666. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  667. url_fskip(pb, size);
  668. //av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
  669. goto resync;
  670. }
  671. if( d[0] >= '0' && d[0] <= '9'
  672. && d[1] >= '0' && d[1] <= '9'){
  673. n= (d[0] - '0') * 10 + (d[1] - '0');
  674. }else{
  675. n= 100; //invalid stream id
  676. }
  677. //parse ##dc/##wb
  678. if(n < s->nb_streams){
  679. AVStream *st;
  680. AVIStream *ast;
  681. st = s->streams[n];
  682. ast = st->priv_data;
  683. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  684. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  685. || st->discard >= AVDISCARD_ALL){
  686. if(ast->sample_size) ast->frame_offset += pkt->size;
  687. else ast->frame_offset++;
  688. url_fskip(pb, size);
  689. goto resync;
  690. }
  691. if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  692. d[2]*256+d[3] == ast->prefix /*||
  693. (d[2] == 'd' && d[3] == 'c') ||
  694. (d[2] == 'w' && d[3] == 'b')*/) {
  695. //av_log(NULL, AV_LOG_DEBUG, "OK\n");
  696. if(d[2]*256+d[3] == ast->prefix)
  697. ast->prefix_count++;
  698. else{
  699. ast->prefix= d[2]*256+d[3];
  700. ast->prefix_count= 0;
  701. }
  702. avi->stream_index= n;
  703. ast->packet_size= size + 8;
  704. ast->remaining= size;
  705. {
  706. uint64_t pos= url_ftell(pb) - 8;
  707. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  708. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  709. }
  710. }
  711. goto resync;
  712. }
  713. }
  714. /* palette changed chunk */
  715. if ( d[0] >= '0' && d[0] <= '9'
  716. && d[1] >= '0' && d[1] <= '9'
  717. && ((d[2] == 'p' && d[3] == 'c'))
  718. && n < s->nb_streams && i + size <= avi->fsize) {
  719. AVStream *st;
  720. int first, clr, flags, k, p;
  721. st = s->streams[n];
  722. first = get_byte(pb);
  723. clr = get_byte(pb);
  724. if(!clr) /* all 256 colors used */
  725. clr = 256;
  726. flags = get_le16(pb);
  727. p = 4;
  728. for (k = first; k < clr + first; k++) {
  729. int r, g, b;
  730. r = get_byte(pb);
  731. g = get_byte(pb);
  732. b = get_byte(pb);
  733. get_byte(pb);
  734. st->codec->palctrl->palette[k] = b + (g << 8) + (r << 16);
  735. }
  736. st->codec->palctrl->palette_changed = 1;
  737. goto resync;
  738. }
  739. }
  740. return -1;
  741. }
  742. /* XXX: we make the implicit supposition that the position are sorted
  743. for each stream */
  744. static int avi_read_idx1(AVFormatContext *s, int size)
  745. {
  746. AVIContext *avi = s->priv_data;
  747. ByteIOContext *pb = s->pb;
  748. int nb_index_entries, i;
  749. AVStream *st;
  750. AVIStream *ast;
  751. unsigned int index, tag, flags, pos, len;
  752. unsigned last_pos= -1;
  753. nb_index_entries = size / 16;
  754. if (nb_index_entries <= 0)
  755. return -1;
  756. /* read the entries and sort them in each stream component */
  757. for(i = 0; i < nb_index_entries; i++) {
  758. tag = get_le32(pb);
  759. flags = get_le32(pb);
  760. pos = get_le32(pb);
  761. len = get_le32(pb);
  762. #if defined(DEBUG_SEEK)
  763. av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  764. i, tag, flags, pos, len);
  765. #endif
  766. if(i==0 && pos > avi->movi_list)
  767. avi->movi_list= 0; //FIXME better check
  768. pos += avi->movi_list;
  769. index = ((tag & 0xff) - '0') * 10;
  770. index += ((tag >> 8) & 0xff) - '0';
  771. if (index >= s->nb_streams)
  772. continue;
  773. st = s->streams[index];
  774. ast = st->priv_data;
  775. #if defined(DEBUG_SEEK)
  776. av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  777. #endif
  778. if(last_pos == pos)
  779. avi->non_interleaved= 1;
  780. else
  781. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  782. if(ast->sample_size)
  783. ast->cum_len += len;
  784. else
  785. ast->cum_len ++;
  786. last_pos= pos;
  787. }
  788. return 0;
  789. }
  790. static int guess_ni_flag(AVFormatContext *s){
  791. int i;
  792. int64_t last_start=0;
  793. int64_t first_end= INT64_MAX;
  794. for(i=0; i<s->nb_streams; i++){
  795. AVStream *st = s->streams[i];
  796. int n= st->nb_index_entries;
  797. if(n <= 0)
  798. continue;
  799. if(st->index_entries[0].pos > last_start)
  800. last_start= st->index_entries[0].pos;
  801. if(st->index_entries[n-1].pos < first_end)
  802. first_end= st->index_entries[n-1].pos;
  803. }
  804. return last_start > first_end;
  805. }
  806. static int avi_load_index(AVFormatContext *s)
  807. {
  808. AVIContext *avi = s->priv_data;
  809. ByteIOContext *pb = s->pb;
  810. uint32_t tag, size;
  811. offset_t pos= url_ftell(pb);
  812. url_fseek(pb, avi->movi_end, SEEK_SET);
  813. #ifdef DEBUG_SEEK
  814. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  815. #endif
  816. for(;;) {
  817. if (url_feof(pb))
  818. break;
  819. tag = get_le32(pb);
  820. size = get_le32(pb);
  821. #ifdef DEBUG_SEEK
  822. printf("tag=%c%c%c%c size=0x%x\n",
  823. tag & 0xff,
  824. (tag >> 8) & 0xff,
  825. (tag >> 16) & 0xff,
  826. (tag >> 24) & 0xff,
  827. size);
  828. #endif
  829. switch(tag) {
  830. case MKTAG('i', 'd', 'x', '1'):
  831. if (avi_read_idx1(s, size) < 0)
  832. goto skip;
  833. else
  834. goto the_end;
  835. break;
  836. default:
  837. skip:
  838. size += (size & 1);
  839. url_fskip(pb, size);
  840. break;
  841. }
  842. }
  843. the_end:
  844. url_fseek(pb, pos, SEEK_SET);
  845. return 0;
  846. }
  847. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  848. {
  849. AVIContext *avi = s->priv_data;
  850. AVStream *st;
  851. int i, index;
  852. int64_t pos;
  853. if (!avi->index_loaded) {
  854. /* we only load the index on demand */
  855. avi_load_index(s);
  856. avi->index_loaded = 1;
  857. }
  858. assert(stream_index>= 0);
  859. st = s->streams[stream_index];
  860. index= av_index_search_timestamp(st, timestamp, flags);
  861. if(index<0)
  862. return -1;
  863. /* find the position */
  864. pos = st->index_entries[index].pos;
  865. timestamp = st->index_entries[index].timestamp;
  866. // av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  867. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  868. /* One and only one real stream for DV in AVI, and it has video */
  869. /* offsets. Calling with other stream indices should have failed */
  870. /* the av_index_search_timestamp call above. */
  871. assert(stream_index == 0);
  872. /* Feed the DV video stream version of the timestamp to the */
  873. /* DV demux so it can synth correct timestamps */
  874. dv_offset_reset(avi->dv_demux, timestamp);
  875. url_fseek(s->pb, pos, SEEK_SET);
  876. avi->stream_index= -1;
  877. return 0;
  878. }
  879. for(i = 0; i < s->nb_streams; i++) {
  880. AVStream *st2 = s->streams[i];
  881. AVIStream *ast2 = st2->priv_data;
  882. ast2->packet_size=
  883. ast2->remaining= 0;
  884. if (st2->nb_index_entries <= 0)
  885. continue;
  886. // assert(st2->codec->block_align);
  887. assert(st2->time_base.den == ast2->rate);
  888. assert(st2->time_base.num == ast2->scale);
  889. index = av_index_search_timestamp(
  890. st2,
  891. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  892. flags | AVSEEK_FLAG_BACKWARD);
  893. if(index<0)
  894. index=0;
  895. if(!avi->non_interleaved){
  896. while(index>0 && st2->index_entries[index].pos > pos)
  897. index--;
  898. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  899. index++;
  900. }
  901. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  902. /* extract the current frame number */
  903. ast2->frame_offset = st2->index_entries[index].timestamp;
  904. if(ast2->sample_size)
  905. ast2->frame_offset *=ast2->sample_size;
  906. }
  907. /* do the seek */
  908. url_fseek(s->pb, pos, SEEK_SET);
  909. avi->stream_index= -1;
  910. return 0;
  911. }
  912. static int avi_read_close(AVFormatContext *s)
  913. {
  914. int i;
  915. AVIContext *avi = s->priv_data;
  916. for(i=0;i<s->nb_streams;i++) {
  917. AVStream *st = s->streams[i];
  918. AVIStream *ast = st->priv_data;
  919. av_free(ast);
  920. av_free(st->codec->palctrl);
  921. }
  922. if (avi->dv_demux)
  923. av_free(avi->dv_demux);
  924. return 0;
  925. }
  926. static int avi_probe(AVProbeData *p)
  927. {
  928. int i;
  929. /* check file header */
  930. for(i=0; avi_headers[i][0]; i++)
  931. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  932. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  933. return AVPROBE_SCORE_MAX;
  934. return 0;
  935. }
  936. AVInputFormat avi_demuxer = {
  937. "avi",
  938. "avi format",
  939. sizeof(AVIContext),
  940. avi_probe,
  941. avi_read_header,
  942. avi_read_packet,
  943. avi_read_close,
  944. avi_read_seek,
  945. };